#include "ys_form_bzgl.h"
#include "ui_ys_form_bzgl.h"
#include "ys_senior_check.h"    //超职级用药
#include "pub_var.h"
#include <QSettings>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>
#include <QSqlError>
#include <QSqlRecord>
#include <QDesktopWidget>
#include <QSqlDriver>
#include <QSet>
#include <QListWidgetItem>
#include <QCamera>
#include <QCameraInfo>
#include <QCameraViewfinder>
#include <QDir>

//const int NEXT_CALL_DAYS = 7;
//QList<QCameraInfo> cameraList;
extern QList<QCameraInfo> cameraList;

Form_ys_bzgl::Form_ys_bzgl(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_ys_bzgl)
{
    ui->setupUi(this);

    initialFinished = false;
    remoteQuery = false;

    //恢复当前窗口位置
    QSettings setIni("clin.ini", QSettings::IniFormat);

    remote_path = setIni.value("database/host_name").toString();

    if(remote_path.isEmpty())
    {
        remote_path = setIni.value("database/m_hostname").toString();
    }

    remote_path = "//" + remote_path + "/pics/pics";

    simple_model = false;
    diag_model = false;

    if(setIni.value("bz/simple_model", 1).toInt() == 1)
    {
        simple_model = true;
    }

    if(setIni.value("bz/diag_model", 1).toInt() == 1)
    {
        diag_model = true;
    }

    if(!simple_model)
    {
        ui->label_4->setVisible(false);
        ui->cbbBzmb->setVisible(false);
        ui->pbModelDelete->setVisible(false);
        ui->pbModeSave->setVisible(false);
    }

    QRect rct = setIni.value("windowState/bzgl").toRect();
    this->setGeometry(rct);
    ui->label_9->setVisible(false);
    ui->rb_last_date->setVisible(false);
    ui->rb_pointed_date->setVisible(false);

    //禁止部分 comboBox 的滚轮事件
    ui->cbb_tr_diag1->installEventFilter(this);
    ui->cbb_tr_diag2->installEventFilter(this);
    ui->cbb_tr_diag3->installEventFilter(this);
    ui->cbb_tr_symptom1->installEventFilter(this);
    ui->cbb_tr_symptom2->installEventFilter(this);
    ui->cbb_tr_symptom3->installEventFilter(this);
    ui->cbbDiag1->installEventFilter(this);
    ui->cbbDiag2->installEventFilter(this);
    ui->cbbDiag3->installEventFilter(this);
    ui->cbb_yz->installEventFilter(this);
    ui->cbb_conclusion->installEventFilter(this);


    ui->cbbRange->clear();
    ui->cbbRange->addItem("西药中成药");
    ui->cbbRange->addItem("耗材");
    ui->cbbRange->addItem("诊疗");

    ui->grp_doct_duty->setVisible(false);

//    ui->scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);  // 禁用水平滚动条
//    ui->scrollArea->setStyleSheet("QScrollBar:horizontal { height: 0px; }");

    qDebug()<<"doctor duty is : "<<pub::dr_duty_range;

    if(pub::dr_duty_range == "中医")
    {
        ui->rb_mode_tr->setChecked(true);
        ui->cbbRange->addItem("中草药");
    }
    else if(pub::dr_duty_range == "西医")
    {
        ui->rb_mode_med->setChecked(true);
    }
    else
    {
        ui->rb_mode_tr_med->setChecked(true);
        ui->cbbRange->addItem("中草药");
    }

    on_rb_mode_med_clicked();


    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qrmt = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);
    md = new QSqlQueryModel(this);
    mdHist = new QSqlQueryModel(this);
    mdRecipe = new QSqlQueryModel(this);
    mdRecipeNew = new QSqlQueryModel(this);
    mdGroupPop = new QSqlQueryModel(this);  //弹出组套
    mdSearchPop = new QSqlQueryModel(this); //弹出检索
    mdGroup = new QStandardItemModel(this);//组套
    md_check = new QSqlQueryModel(this);//辅助检查
    md_pics = new QSqlQueryModel(this);//图像

    cap_setup = NULL;//摄像头设置

    ui->tvGroup->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tvGroup->setExpandsOnDoubleClick(true);

    //网络参数
    request.setUrl(QUrl(pub::hos_ybjy));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    request_zjzf.setUrl(QUrl(pub::zj_push_ip));
    request_zjzf.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    sq = "select si_code from com_doctor_compare where empl_code = '" + pub::usr_code + "'";
    qro->exec(sq);
    qro->next();

    ybysdm = qro->value(0).toString();  //医保医师代码
    //ui->cbbPos

    sq = "select name from com_dict_com where mark = 'doct' and dic_type = '过敏史' order by ord";
    fillCombo(ui->cbbGms, sq, -1);  //

    sq = "select name from com_dict_com where mark = 'doct' and dic_type = '既往史' order by ord";
    fillCombo(ui->cbbJws, sq, -1);  //

    sq = "select name from com_dict_com where mark = 'com' and dic_type = '代开药人员关系' order by ord";
    fillCombo(ui->cbbTrusteeRlt, sq, -1);  //

    sq = "select name from com_dict_com where mark = 'com' and dic_type = '诊疗结论' order by ord";
    fillCombo(ui->cbb_conclusion, sq, 0);  //

    sq = "select item_name from com_dict_icpc where instr(dept_code, '"
            + pub::dp_code + "') > 0 and type = '0'";   //concat(concat(item_name,'^'),icpc_code)
    fillCombo(ui->cbbReason, sq, -1);   //就诊原因

    restore_diag_comb("111");


    sq = "select mbmc from ys_bz_e_model "
         " where mblx='bz' and dept_code = '" + pub::dp_code + "' order by mbmc";
    fillCombo(ui->cbbBzmb, sq, -1);//病志模板

    sq = "select mbmc from ys_bz_e_model "
         " where mblx='jy' and dept_code = '" + pub::dp_code + "' order by mbmc";
    fillCombo(ui->cbbJchy, sq, -1);//检查化验

    //sq = "select a.dept_name from com_department a, com_dict_com b where a.dept_code = b.mark and "
    //     " b.dic_type = '执行科室' and b.dept_code = '"+pub::dp_code+"'";

    sq = "select name from com_dict_com where dic_type = '执行科室' and dept_code = '"
            +pub::dp_code+"' order by code";
    fillCombo(ui->cbbExecDept, sq, -1);//执行科室

    //sq = "select name from com_dict_com where dic_type='使用单位' ";
    //fillCombo(ui->cbbDoseUnit, sq, -1);//

    sq = "select name from com_dict_com where dic_type='包装单位' ";
    fillCombo(ui->cbbPackUnit, sq, -1);//

    sq = "select name from com_dict_com where dic_type='给药途径' ";
    fillCombo(ui->cbbUsage, sq, -1);//

    sq = "select name from com_dict_com where dic_type='频次' ";
    fillCombo(ui->cbbFreq, sq, -1);//

    sq = "select left(name,12), name from com_dict_com where dic_type='医嘱' and dept_code = '"
            +pub::dp_code+"' order by code";
    ui->cbb_yz->addItem("下拉选择模板医嘱");
    fillCombo(ui->cbb_yz, sq, 0, false,& doct_ord);//

    fillGroup();

    ui->deRegDate->setDate(QDate().currentDate());

    ui->cbNew->setVisible(false);   //提取未接诊患者列表
    ui->pbCheck3101->setVisible(false);  //医保校验

    //ui->cbToday->setVisible(false);

    ui->lbDept->setStyleSheet("color: blue;");
    ui->lbDept->setText( pub::dp_name + " | " + pub::usr_name + " | " + pub::dr_codg);

    pop_3103 = new Ys_bzgl_3103();
    dlgDelay = new Pub_pop_delay();
    dlgGetValue = new Pub_pop_get_value();
    dlgGetItem = new Pub_pop_get_item();
    sqlThread = new sqThread();
    connect( sqlThread, &sqThread::message, this, &Form_ys_bzgl::threadMsg);

    sq = "create temporary table if not exists tmp_group_content "
         "("
         "ext_code varchar(5)," //组合项目标志 1 组合， 0 单独
         "PACKAGE_CODE VARCHAR(15)," //组合代码
         "PACKAGE_NAME VARCHAR(50)," //组合名称
         "item_code VARCHAR(12) , "
         "item_name VARCHAR(100) ,"
         "frequency VARCHAR(20) , "
         "usages VARCHAR(20) , "
         "once_dose decimal(10,3), "
         "dose_unit VARCHAR(16) ,"
         "qty decimal(6) , "
         "qty_unit VARCHAR(10) , "
         "seq int not null, "
         "item_type char(1) ,"
         "exe_deptcode varchar(10) , "
         "price decimal(10,4), "
         "specs VARCHAR(50) ,"
         "drug_quality char(5),"
         "DOSE_MODEL_CODE varchar(45),"
         "SELF_MADE varchar(45),"
         "FEE_CODE varchar(45),"
         "CLASS_CODE varchar(45),"
         "BASE_DOSE varchar(45),"
         "FREQUENCY_CODE varchar(45),"
         "USAGE_CODE varchar(45),"
         "USE_NAME varchar(45),"
         "pack_qty integer, "
         "amount decimal(10,2), "
         "center_grade integer,"
         "center_code varchar(50)"
         ")";

    qDebug()<<"create temporary table tmp_group_content : "<<sq;
    if(!qrm->exec(sq)){
        QMessageBox::information(NULL, "Note", "create temporary table tmp_group_content  failed.");

    }

    sq = "create temporary table if not exists tmp_recipe "
         "("
         "PACKAGE_CODE VARCHAR(15),"
         "PACKAGE_NAME VARCHAR(50),"
         "item_code VARCHAR(12) unique not null, "
         "item_name VARCHAR(100) not null,"
         "frequency VARCHAR(20) , "
         "usages VARCHAR(20) , "
         "once_dose decimal(10,3), "
         "dose_unit VARCHAR(16) ,"
         "qty decimal(6) not null, "
         "qty_unit VARCHAR(10) not null, "
         "seq int not null, "
         "item_type char(1) not null,"
         "ext_code varchar(10),"
         "exe_deptcode varchar(10) , "
         "diag1 varchar(45),"
         "diag2 varchar(45),"
         "diag3 varchar(45), "
         "diag1c varchar(45),"
         "diag2c varchar(45),"
         "diag3c varchar(45),"
         "price decimal(10,4) not null, "
         "specs VARCHAR(50) ,"
         "drug_quality char(5),"
         "DOSE_MODEL_CODE varchar(45),"
         "SELF_MADE varchar(45),"
         "FEE_CODE varchar(45),"
         "CLASS_CODE varchar(45),"
         "BASE_DOSE varchar(45),"
         "FREQUENCY_CODE varchar(45),"
         "USAGE_CODE varchar(45),"
         "USE_NAME varchar(45),"
         "pack_qty integer, "
         "amount decimal(10,2), "
         "center_grade integer, "
         "freq_days double, "
         "recipe_days integer,"
         "center_code varchar(50)"
         ")";
    qDebug()<<"create temporary table tmp_recipe： "<<sq;
    if(!qrm->exec(sq)){
        QMessageBox::information(NULL, "Note", "create temporary table tmp_recipe failed.");

    }

    //on_tabWidget_currentChanged(0);
    cur_item_code = "";

    tmDiag = new QTimer(this);
    tmTvWidth = new QTimer(this);
    connect(tmDiag, &QTimer::timeout, this, &Form_ys_bzgl::tmDiagTimeout);
    connect(this, &Form_ys_bzgl::trigTimer, this, &Form_ys_bzgl::tmDiagTimerStarter);

    connect(tmTvWidth, &QTimer::timeout, this, &Form_ys_bzgl::tmTvWidthReset);

    ui->tabWidget->setCurrentIndex(0);

    //设置各页面停止
    ui->tab_recipe_new->setEnabled(false);
    ui->tab_history->setEnabled(false);
    ui->tab_base->setEnabled(false);
    ui->tab_recipe_today->setEnabled(false);
    ui->tab_aux_check->setEnabled(false);

    //中药剂数
    ui->lb_tr_days->setHidden(true);
    ui->le_tr_days->setHidden(true);
    ui->le_dose_unit->setReadOnly(true);


    my_msg.setWindowTitle("模版使用方式");

    // 添加三个按钮
    bt_overwriter = my_msg.addButton("覆盖", QMessageBox::ActionRole);
    bt_append = my_msg.addButton("追加", QMessageBox::ActionRole);
    bt_ignore = my_msg.addButton("忽略", QMessageBox::ActionRole);

    camera_initialized = false;
    pic_num = 0;

    //图片文件路径
    pic_path = pub::base_path + "/pics";
    QDir d = QDir(pic_path);

    if(!d.exists())
    {
        d.mkdir(pic_path);
    }
    else
    {
        //清空
        d.setNameFilters( QStringList("*.jpg") );
        QStringList files = d.entryList();  //read filenames

        for(int i = 0; i < files.size() ; i++)
        {
            QFile f(pic_path + "/" + files[i]);
            f.remove();
        }
    }

    camera = nullptr;
    viewfinder = nullptr;
    imageCapture = nullptr;

    view = new QGraphicsView(this);
    scene = new QGraphicsScene(this);
    pixmapItem = nullptr;
    view->setScene(scene);
    ui->hl_view->addWidget(view);

    //view->setFixedSize(800, 600);  // 固定显示区域大小

    connect(ui->tb_zoom_fit, &QToolButton::clicked, this, &Form_ys_bzgl::pic_fitToView); // 连接适应视图按钮
    connect(ui->tb_zoom_in, &QToolButton::clicked, this, &Form_ys_bzgl::pic_zoomIn);
    connect(ui->tb_zoom_out, &QToolButton::clicked, this, &Form_ys_bzgl::pic_zoomOut);

    initialFinished = true;

    on_tabWidget_currentChanged(0);

    tmTvWidth->start(1000);

    qDebug()<<"Initial finished.\n";

}

Form_ys_bzgl::~Form_ys_bzgl()
{
    delete ui;

    delete qrm;
    delete qrmt;
    delete qro;
    delete qrot;
    delete pop_3103;
    delete dlgDelay;
    delete dlgGetValue;
    delete dlgGetItem;
    delete sqlThread;

    if(cap_setup != NULL)
    {
        //进入过图像模块
        delete cap_setup;

        if(camera != nullptr)
        {
            camera->stop();
            camera->unload();
            delete camera;
            camera = nullptr;
        }

        if(viewfinder != nullptr)
        {
            delete viewfinder;
            viewfinder = nullptr;
        }

        if(imageCapture != nullptr)
        {
            delete imageCapture;
            imageCapture = nullptr;
        }

    }
}

bool Form_ys_bzgl::eventFilter(QObject *obj, QEvent *event)
{
    // 检查事件是否是滚轮事件，并且事件来源是我们要过滤的comboBox
       if (event->type() == QEvent::Wheel)
       {
           if (qobject_cast<QComboBox*>(obj))
           {
               // 忽略滚轮事件
               return true;
           }
       }
       // 其他事件交给基类处理
       return QWidget::eventFilter(obj, event);
}

void Form_ys_bzgl::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/bzgl", QVariant(this->geometry()));

    if(ui->rb_mode_tr->isChecked())
    {
        setIni.setValue("doct/mode", "tr");
    }
    else if(ui->rb_mode_med->isChecked())
    {
        setIni.setValue("doct/mode", "med");
    }
    else
    {
        setIni.setValue("doct/mode", "tr_med");
    }

    emit destroyW( "ys_bzgl" );

}

void Form_ys_bzgl::fillGroup()
{
    mdGroup->clear();

    sq = "select folder_name,folder_id from met_com_groupfolder where dept_code = '"+pub::dp_code+"'"
         " and group_type = '1' and group_kind = '2'  order by folder_ord ";
    qro->exec(sq);

    QList<QStandardItem *> itemListRow, itemListColumn;//, itemListFN, itemlistFI;
    QStandardItem  *it, *base;//*itemParent, *itemChild,

    while(qro->next())
    {
        QString fdnm = qro->value(0).toString();
        QString fdid = qro->value(1).toString();

        it = new QStandardItem(fdnm);
        mdGroup->appendRow(it);
        it = new QStandardItem(fdid);
        itemListColumn << it;
    }
    mdGroup->appendColumn(itemListColumn);

    for(int i = 0; i< mdGroup->rowCount(); i++)
    {
        base = mdGroup->item(i,0);
        it = mdGroup->item(i,1);
        sq = "select groupname,groupid from MET_COM_GROUP t "
             " where (remark is null or remark = '0') and folder_id = '";
        sq += it->text() + "' order by group_ord";
        qrot->exec(sq);
        itemListRow.clear();
        itemListColumn.clear();
        while (qrot->next())
        {
            QString grnm = qrot->value(0).toString();
            QString grid = qrot->value(1).toString();
            it = new QStandardItem(grnm);
            itemListRow << it;
            it = new QStandardItem(grid);
            itemListColumn << it;

        }
        base->appendRows(itemListRow);
        base->appendColumn(itemListColumn);
    }

    mdGroup->setHeaderData(0, Qt::Horizontal, "常用组套");
    ui->tvGroup->setModel(mdGroup);
    //ui->tvGroup->setHeader()
    ui->tvGroup->setColumnHidden(1,true);

}

void Form_ys_bzgl::on_pbExit_clicked()
{
    if(remoteQuery)
    {
        QMessageBox::warning(this, "注意", "正在进行远程查询，请稍候......");
        qApp->processEvents();
        return;
    }
    close();
}

void Form_ys_bzgl::on_pbFresh_clicked()
{
    if(remoteQuery)
    {
        QMessageBox::warning(this, "注意", "正在进行远程查询，请稍候......");
        qApp->processEvents();
        return;
    }

    md->setQuery("");

    ui->tabWidget->setCurrentIndex(0);

    if(ui->leCardNo->text().trimmed().isEmpty())
    {
        ui->cbCardNo->setChecked(false);
    }else{
        ui->cbCardNo->setChecked(true);
        ui->cbRegDate->setChecked(false);
        ui->cbOwn->setChecked(false);
    }
    if(ui->leNameS->text().trimmed().isEmpty())
    {
        ui->cbName->setChecked(false);
    }else{
        ui->cbName->setChecked(true);
        ui->cbRegDate->setChecked(false);
        ui->cbOwn->setChecked(false);
    }
    if(ui->leIdennoS->text().trimmed().isEmpty())
    {
        ui->cbIdenno->setChecked(false);
    }else{
        ui->cbIdenno->setChecked(true);
        ui->cbRegDate->setChecked(false);
        ui->cbOwn->setChecked(false);
    }

    if(!ui->cbRegDate->isChecked())
    {
        if(!ui->cbCardNo->isChecked() && !ui->cbName->isChecked()  && !ui->cbIdenno->isChecked())
        {
            QMessageBox::warning(this, "注意", "不限日期查询，必须指定姓名、病志号或身份证！");
            return;
        }
    }
    //
    sq = " select to_char(reg.reg_date, 'yyyy-mm-dd') 挂号日期, "
         " reg.card_no 病志号, reg.name 姓名, " //0-2
         " reg.clinic_code, reg.card_no, reg.mcard_no, reg.invoice_no, "//3-6
         " reg.idenno, reg.rela_phone, reg.address, reg.sex_code, "//7-10
         " to_char(reg.birthday, 'yyyy-mm-dd') , reg.pact_code, "//11-12
         //" reg.pact_name  费别, "//13
         " case when reg.pact_code = '1' then '现金' else '市保' end  费别, "//13
         " reg.see_docd, to_char(reg.reg_date, 'yyyy-mm-dd hh24:mi:ss'),"//14-15
         " case when reg.sex_code = 'M' then '男' else '女' end,"
         " emp.empl_name";//17

    sq += " from FIN_OPR_REGISTER reg"
          " left join com_employee emp on reg.see_docd = emp.empl_code ";

    sq += " where reg.valid_flag = '1' and reg.dept_code = '"+ pub::dp_code+"' ";

    if(ui->cbOwn->isChecked()) //本人患者
    {
        sq += " and (reg.see_docd='"
                + pub::usr_code + "' or (reg.doct_code='"
                + pub::usr_code + "' and reg.see_docd is null )) ";
    }

    if(ui->cbCardNo->isChecked())
    {
        //指定病志号
        sq += " and reg.card_no like '%" + ui->leCardNo->text().trimmed() + "' ";
    }

    if(ui->cbIdenno->isChecked())
    {
        //指定身份证
        sq += " and reg.idenno like '%" + ui->leIdennoS->text().trimmed().toUpper() + "%' ";
    }

    if(ui->cbName->isChecked())
    {
        //指定姓名
        sq += " and reg.name like '%" + ui->leNameS->text().trimmed() + "%' ";
    }

    if(ui->cbRegDate->isChecked())
    {
        //指定日期
        sq += " and trunc(reg.reg_date) = to_date('"
                + ui->deRegDate->date().toString("yyyy-MM-dd") + "','yyyy-mm-dd') ";
    }

    sq += " order by reg.reg_date desc ";

    qDebug()<<"search patient for operate : " << sq;
    md->setQuery(sq, pub::db_o);

    ui->tvList->setModel(md);

    int w = ui->tvList->horizontalHeader()->width();
    pub::setColumnWidth(ui->tvList, "0.28^0.3^0.22^0^0^0^0^0^0^0^0^0^0^0.13^0^0", w );

    on_pbClear_clicked();

    process_out_grade_apply();

}

void Form_ys_bzgl::process_out_grade_apply()
{
    sq = " select event_sendder , clinic_code from com_events "
         " where event_user = '%1' and event_id = 'out_grade_apply'";
    sq = sq.arg(pub::usr_code);
    qDebug()<<"检查有没有超职级用药申请："<<sq<<"\n";
    qro->exec(sq);
    if(qro->next())
    {
        //发送消息
        trig_senior();
    }
}

void Form_ys_bzgl::on_tvList_clicked(const QModelIndex &index)
{

    //单击患者列表
    qDebug()<<"患者列表单击：on_tvList_clicked(const QModelIndex &index)\n";

    on_pbClear_clicked();

    QDate dt_reg = index.siblingAtColumn(15).data(0).toDate();
    QDate dt_cur = QDate::currentDate();

    int dt_distance = dt_reg.daysTo(dt_cur);

    if( dt_distance < 4)
    {
        ui->tab_recipe_new->setEnabled(true);
    }
    else
    {
        ui->tab_recipe_new->setEnabled(false);
    }

    ui->tab_history->setEnabled(true);
    ui->tab_base->setEnabled(true);
    ui->tab_recipe_today->setEnabled(true);
    ui->tab_aux_check->setEnabled(true);

    mpPatientInfo.insert("date", index.siblingAtColumn(0).data(0).toString());

    QString ed_dt = index.siblingAtColumn(0).data(0).toString();
    ui->le_current_date->setText(ed_dt);
    ui->le_current_doct->setText(index.siblingAtColumn(17).data(0).toString());

    mpPatientInfo["see_docd"] = index.siblingAtColumn(14).data(0).toString();


    mpPatientInfo["reg_date"] = index.siblingAtColumn(15).data(0).toString();
    mpPatientInfo["pact_code"] = index.siblingAtColumn(12).data(0).toString();
    mpPatientInfo["pact_name"] = index.siblingAtColumn(13).data(0).toString();
    mpPatientInfo["clinic_code"] = index.siblingAtColumn(3).data(0).toString();

    mpPatientInfo.insert("card_no", index.siblingAtColumn(1).data(0).toString());
    mpPatientInfo.insert("name", index.siblingAtColumn(2).data(0).toString());

    //mpPatientInfo.insert("card_no", index.siblingAtColumn(4).data(0).toString());
    mpPatientInfo.insert("mcard_no", index.siblingAtColumn(5).data(0).toString());
    //mpPatientInfo.insert("invoice_no", index.siblingAtColumn(6).data(0).toString());
    mpPatientInfo.insert("idenno", index.siblingAtColumn(7).data(0).toString());
    mpPatientInfo.insert("rela_phone", index.siblingAtColumn(8).data(0).toString());
    mpPatientInfo.insert("address", index.siblingAtColumn(9).data(0).toString());
    mpPatientInfo.insert("sex_code", index.siblingAtColumn(10).data(0).toString());
    mpPatientInfo.insert("birthday", index.siblingAtColumn(11).data(0).toString());
    mpPatientInfo.insert("gender", index.siblingAtColumn(16).data(0).toString());

    dlgDelay->setText("正在提取数据。。。");
    dlgDelay->setModal(true);
    dlgDelay->setNeedClose(false);
    dlgDelay->show();
    qApp->processEvents();

    //
    if(mpPatientInfo["sex_code"] == "F")
    {
        ui->frm_menstr->setHidden(false);
    }
    else
    {
        ui->frm_menstr->setHidden(true);
    }

    //

    QString clinic_code_tmp;//用于查询最后一个有效病志数据

    if(ui->ckb_refine_recorder->isChecked())
    {
        qDebug()<<"修订历史记录\n";
        //修订历史记录
        ui->tab_recipe_new->setEnabled(false);

        //按指定日期查询
        clinic_code_tmp = index.siblingAtColumn(3).data(0).toString();
        qDebug()<<"按指定日期查询,clinic_code 为"<<clinic_code_tmp<<"\n";
    }
    else
    {
        //检查是否发生过退号
        sq = " select reg.clinic_code "
             " from fin_opr_register reg"
             " left join com_employee emp on emp.empl_code = reg.see_docd "
             " where "
             " reg.valid_flag = '1' ";
        sq += " and reg.card_no = '" + mpPatientInfo["card_no"] + "' ";
        sq += " and reg.clinic_code = '" + mpPatientInfo["clinic_code"] + "' ";
        sq += " and reg.dept_code = '" + pub::dp_code + "' ";
        sq += " order by reg.reg_date desc";

        qDebug()<<"检查clinic_code "<<mpPatientInfo["clinic_code"]<<" 是否发生退号 ： "<<sq<<"\n";
        qrot->exec(sq);

        if(!qrot->next())
        {
            QMessageBox::warning(this, "注意", "当前挂号记录已经退号，请刷新之后再试！");
            dlgDelay->setNeedClose(true);
            dlgDelay->closeWindow();
            return;
        }

        //电话有可能新保存过，另外，为防止医生未刷新列表期间患者发生退号
        //所以这里重新提取数据
        sq = " select reg.rela_phone, "
             " reg.clinic_code, "
             " reg.see_docd, "
             " to_char(reg.reg_date, 'yyyy-mm-dd hh24:mi:ss') reg_dt, "
             " reg.pact_code, "
             " reg.pact_name ,"
             " emp.empl_name"
             " from fin_opr_register reg"
             " left join com_employee emp on emp.empl_code = reg.see_docd "
             " where "
             " reg.valid_flag = '1' ";
             //" and idenno ='"+mpPatientInfo["idenno"]+"' ";
        sq += " and reg.card_no = '" + mpPatientInfo["card_no"] + "' ";
        sq += " and reg.dept_code = '" + pub::dp_code + "' ";
        sq += " order by reg.reg_date desc";

        qDebug()<<"提取最后一次有效挂号信息 ： "<<sq;

        qrot->exec(sq);
        if(!qrot->next())
        {
            QMessageBox::warning(this, "注意", "挂号信息发生变更，请刷新之后再试！");
            dlgDelay->setNeedClose(true);
            dlgDelay->closeWindow();
            return;
        }

        mpPatientInfo["rela_phone"] = qrot->value("rela_phone").toString();

        //ui->tab_recipe_new->setEnabled(true);
        mpPatientInfo.insert("see_docd", qrot->value("see_docd").toString());
        mpPatientInfo.insert("reg_date", qrot->value("reg_dt").toString());
        mpPatientInfo.insert("pact_code", qrot->value("pact_code").toString());
        mpPatientInfo.insert("pact_name", qrot->value("pact_name").toString());
        mpPatientInfo.insert("clinic_code", qrot->value("clinic_code").toString());

        ed_dt = qrot->value("reg_dt").toString();

        ui->le_current_date->setText(ed_dt.mid(0, 10));
        ui->le_current_doct->setText(qrot->value("empl_name").toString());

        //
        clinic_code_tmp = qrot->value("clinic_code").toString();

        //按最后有效日期查询
        if(qrot->value("see_docd").toString().isEmpty())
        {
            //接诊医师为空，为本日第一次进入。取上一个挂号日期数据
            if(qrot->next())
            {
                clinic_code_tmp = qrot->value("clinic_code").toString();
                qDebug()<<"提取前一次挂号的clinic_code，"<<clinic_code_tmp<<"\n";
            }
            else
            {
                qDebug()<<"当前挂号无历史记录。\n";
            }
        }

    }

    if(mpPatientInfo["pact_code"] == "2") //医保患者可以选择开药模式
    {
        //ui->groupBox_5->setEnabled(true);
        ui->rb_reci_ct_insu->setEnabled(true);
        ui->rb_reci_ct_cash->setEnabled(true);
        ui->rb_reci_ct_insu->setChecked(true);
    }
    else
    {
        //ui->groupBox_5->setEnabled(false);
        ui->rb_reci_ct_insu->setEnabled(false);
        ui->rb_reci_ct_cash->setEnabled(false);
        ui->rb_reci_ct_cash->setChecked(true);
    }

    ui->leName->setText(mpPatientInfo["name"]);
    ui->leGend->setText(mpPatientInfo["gender"]);
    QDate birth = QDate::fromString(mpPatientInfo["birthday"], "yyyy-MM-dd") ;
    QDate now = QDate::currentDate();
    int age = birth.daysTo(now);
    ui->leAge->setText(QString::number( (age/365.25) , 'f', 1) );
    mpPatientInfo.insert("age", ui->leAge->text());
    ui->leIdenno->setText(mpPatientInfo["idenno"]);
    ui->lePhone->setText(mpPatientInfo["rela_phone"]);
    ui->lePatientType->setText(mpPatientInfo["pact_name"]);

    //病志相关信息
    sq = "select hzzs, xbs,xbs_tr, "    //主诉，现病史，刻下症
         "jws, gms, "//既往，过敏
         "jzyy, jzyyc, "//就诊原因，代码
         "zd1, zd1c, zd2, zd2c, zd3, zd3c ,"//诊断，代码
         "tgjc,tgjc_tr, zybz, yz, zljl,"//西医查体，中医查体， 中医辩证，医嘱，诊疗结论
         " rlts, trustee_name, trustee_tel, trustee_certno, "//代取药人关系，经手人姓名、电话、身份证
         "zyzd1, zyzd2, zyzd3, zyzh1, zyzh2, zyzh3, "//中医诊断，代码
            " family_hist,person_hist,menstr_hist,treat_tr,similar_syndrom "
         " from ys_bz_e_rec where clinic_code = '%1' ";

    //sq = sq.arg( mpPatientInfo["clinic_code"] );
    sq = sq.arg( clinic_code_tmp );

    qDebug()<<"提取最后一次挂号关联的病志相关信息 : "<<sq;

    qrm->exec(sq);
    QString diag1,diag2,diag3;

    if(qrm->next())
    {
        initialFinished = false;
        ui->leHzzs->setText(qrm->value("hzzs").toString());
        ui->pt_current_symp->setPlainText(qrm->value("xbs").toString());
        ui->leJws->setText(qrm->value("jws").toString());
        ui->leGms->setText(qrm->value("gms").toString());
        ui->pt_body_check->insertPlainText(qrm->value("tgjc").toString());
        ui->le_menstr->setText(qrm->value("menstr_hist").toString());
        ui->pt_person_history->insertPlainText(qrm->value("person_hist").toString());
        ui->pt_family_history->insertPlainText(qrm->value("family_hist").toString());
        //ui->pt_body_check->insertPlainText(qrm->value("tgjc").toString());

        ui->pt_medical_advice->setPlainText(qrm->value("yz").toString());
        ui->cbbReason->setCurrentText( qrm->value("jzyy").toString() );

        //if(mpPatientInfo["pact_code"] == "2") //医保患者代取药信息
        {
            ui->leTrustee->setText(qrm->value("trustee_name").toString());
            ui->leTrusteeI->setText(qrm->value("trustee_certno").toString());
            ui->leTrusteeP->setText(qrm->value("trustee_tel").toString());
            ui->cbbTrusteeRlt->setCurrentText(qrm->value("rlts").toString());
        }

        diag1 = qrm->value("zd1").toString();
        diag2 = qrm->value("zd2").toString();
        diag3 = qrm->value("zd3").toString();

        initialFinished = true;

        reload_med_rec = true;

        if(!diag1.isEmpty())
        {
            ui->cbbDiag1->setCurrentText(diag1);
            //ui->leDiag1->setText(diag1);
            ui->le_diag1->setText(diag1);
            ui->ckbDiag1->setEnabled(true);
            ui->ckbDiag1->setChecked(true);
        }

        if(!diag2.isEmpty())
        {
            ui->cbbDiag2->setEnabled(true);
            ui->cbbDiag2->setCurrentText(diag2);
            //ui->leDiag2->setText(diag2);
            ui->le_diag2->setText(diag2);
            ui->ckbDiag2->setEnabled(true);
            ui->ckbDiag2->setChecked(true);

        }

        if(!diag3.isEmpty())
        {
            ui->cbbDiag3->setEnabled(true);
            ui->cbbDiag3->setCurrentText(diag3);
            //ui->leDiag3->setText(diag3);
            ui->le_diag3->setText(diag3);
            ui->ckbDiag3->setEnabled(true);
            ui->ckbDiag3->setChecked(true);
        }

        if(ui->rb_mode_tr->isChecked() || ui->rb_mode_tr_med->isChecked())
        {
            //中医或中西医, 提取上次的中医相关内容

            ui->pt_body_check_tr->insertPlainText(qrm->value("tgjc_tr").toString());
            ui->pt_similar_syndrom->setPlainText(qrm->value("similar_syndrom").toString());
            ui->pt_treat_tr->setPlainText(qrm->value("treat_tr").toString());

            ui->cbb_tr_diag1->setCurrentText( qrm->value("zyzd1").toString() );
            ui->cbb_tr_diag2->setCurrentText( qrm->value("zyzd2").toString() );
            ui->cbb_tr_diag3->setCurrentText( qrm->value("zyzd3").toString() );

            ui->cbb_tr_symptom1->setCurrentText( qrm->value("zyzh1").toString() );
            ui->cbb_tr_symptom2->setCurrentText( qrm->value("zyzh2").toString() );
            ui->cbb_tr_symptom3->setCurrentText( qrm->value("zyzh3").toString() );

            ui->pt_tr_diag->setPlainText(qrm->value("zybz").toString());

        }

        reload_med_rec = false;

        ui->cbb_conclusion->setCurrentText(qrm->value("zljl").toString());
        //if(qrm->value("zljl").toString().isEmpty())
        if(ui->cbb_conclusion->currentText().isEmpty())
        {
            ui->cbb_conclusion->setCurrentIndex(0);
        }

//        initialFinished = true;
    }
    else
    {
        qDebug()<<"首诊患者无病历记载。\n";
        reload_med_rec = false;
    }

    if( !mpPatientInfo["see_docd"].isEmpty()
            && mpPatientInfo["see_docd"] != pub::usr_code)
    {
        //非本人接诊记录
        qDebug()<<"非本人接诊记录。\n";
    }
    else
    {
        if(ui->rb_mode_tr->isChecked() || ui->rb_mode_tr_med->isChecked())
        {
            //本次中医接诊, 上次西医接诊或中医诊断不完整，通过中西医诊断关联提取相关内容
            qDebug()<<"本次中医接诊, 上次西医接诊或中医诊断不完整，通过中西医诊断关联提取相关内容\n";

            if(diag1.isEmpty() || diag_complete(ui->cbbDiag1, ui->cbb_tr_diag1,ui->cbb_tr_symptom1) )
            {
                //西医诊断空，或中医已经完成，不需要处理
                qDebug()<<"诊断1，西医诊断空，或中医已经完成。\n";
            }
            else
            {
                sq = " select med_diag_code from com_diag_med_tr"
                     " where med_diag_name = '" + ui->cbbDiag1->currentText() + "'";
                qDebug()<<"通过中西医诊断关联提取相关信息:"<<sq<<"\n";

                qrm->exec(sq);
                if(qrm->next())
                {
                    cbb_med_text_changed(diag1,
                                     ui->cbbDiag1,ui->cbbDiag2,ui->cbbDiag3,
                                     ui->le_diag1,
                                     ui->cbb_tr_diag1,ui->cbb_tr_symptom1,
                                     ui->cbb_tr_diag2,ui->cbb_tr_symptom2,true);
                }
                else
                {
                    QMessageBox::information(this, "注意", "前一次的诊断 "
                                             + ui->cbbDiag1->currentText()
                                             + " 在当前模板系统中找不到对应记录！");
                    ui->cbbDiag1->clear();
                }

            }

            if(diag2.isEmpty() || diag_complete(ui->cbbDiag2, ui->cbb_tr_diag2,ui->cbb_tr_symptom2) )
            {
                //西医诊断空，或中医已经完成
                qDebug()<<"诊断2，西医诊断空，或中医已经完成。\n";
            }
            else
            {
                sq = "select med_diag_code from com_diag_med_tr"
                     " where med_diag_name = '" + ui->cbbDiag2->currentText() + "'";
                qrm->exec(sq);
                if(qrm->next())
                {
                cbb_med_text_changed(diag2,
                                 ui->cbbDiag2,ui->cbbDiag3,ui->cbbDiag1,
                                 ui->le_diag2,
                                 ui->cbb_tr_diag2,ui->cbb_tr_symptom2,
                                 ui->cbb_tr_diag3,ui->cbb_tr_symptom3,false);
                }
                else
                {
                    QMessageBox::information(this, "注意", "前一次的诊断 "
                                             + ui->cbbDiag2->currentText()
                                             + " 在当前模板系统中找不到对应记录！");
                    ui->cbbDiag1->clear();
                }
            }

            if(diag3.isEmpty() || diag_complete(ui->cbbDiag3, ui->cbb_tr_diag3,ui->cbb_tr_symptom3) )
            {
                //西医诊断空，或中医已经完成
                qDebug()<<"诊断3，西医诊断空，或中医已经完成。\n";
            }
            else
            {
                sq = "select med_diag_code from com_diag_med_tr"
                     " where med_diag_name = '" + ui->cbbDiag3->currentText() + "'";
                qrm->exec(sq);
                if(qrm->next())
                {
                    cbb_med_text_changed(diag3,
                                         ui->cbbDiag3,ui->cbbDiag1,ui->cbbDiag2,
                                         ui->le_diag3,
                                         ui->cbb_tr_diag3,ui->cbb_tr_symptom3,
                                         ui->cbb_tr_diag1,ui->cbb_tr_symptom1,false);
                }
                else
                {
                    QMessageBox::information(this, "注意", "前一次的诊断 "
                                             + ui->cbbDiag3->currentText()
                                             + " 在当前模板系统中找不到对应记录！");
                    ui->cbbDiag1->clear();
                }
            }
        }
    }

    if(diag_complete(ui->cbbDiag1, ui->cbb_tr_diag1,ui->cbb_tr_symptom1))
    {
        ui->cbbDiag2->setEnabled(true);
        ui->cbb_tr_diag2->setEnabled(true);
        ui->cbb_tr_symptom2->setEnabled(true);
    }

    if(diag_complete(ui->cbbDiag2, ui->cbb_tr_diag2,ui->cbb_tr_symptom2))
    {
        ui->cbbDiag3->setEnabled(true);
        ui->cbb_tr_diag3->setEnabled(true);
        ui->cbb_tr_symptom3->setEnabled(true);
    }

    //旧系统保存的病志，个人史等字段为空，补齐
    if(ui->pt_person_history->toPlainText().isEmpty())
    {
        qDebug()<<"补充旧病志缺项\n";
        if(!diag1.isEmpty())
        {
            //根据第一诊断提取相关内容
            sq = "select person_hist, hist_symptom,allergy_hist,menstr_hist,family_hist"
                 " from com_diag_med_tr "
                 " where med_diag_name = '" + diag1 + "'";
            qrm->exec(sq);

            if(qrm->next())
            {
                if(ui->pt_person_history->toPlainText().isEmpty())
                {
                    ui->pt_person_history->setPlainText(qrm->value("person_hist").toString());
                }

                if(ui->leJws->text().isEmpty())
                {
                    ui->leJws->setText(qrm->value("hist_symptom").toString());
                }

                if(ui->leGms->text().isEmpty())
                {
                    ui->leGms->setText(qrm->value("allergy_hist").toString());
                }

                if(mpPatientInfo["sex_code"] == "F" && ui->le_menstr->text().isEmpty())
                {
                    ui->le_menstr->setText(qrm->value("menstr_hist").toString());
                }

                if(ui->pt_family_history->toPlainText().isEmpty())
                {
                    ui->pt_family_history->setPlainText(qrm->value("family_hist").toString());
                }
            }
            else
            {
                qDebug()<<"诊断名称无效，无法提取默认内容";
            }
        }
    }

    if(!ui->rb_mode_med->isChecked()  //非西医
            && ui->pt_similar_syndrom->toPlainText().isEmpty() //类证空
            && ui->leTrustee->text().isEmpty() //非代取药
            )
    {
        //非西医，类证空
        qDebug()<<"非西医，类证空，非代取药\n";

        QString diag_code = getNatCode(ui->cbb_tr_diag1->currentText(), "8");  //2:西医诊断，8：中医诊断
        QString symp_code = getNatCode(ui->cbb_tr_symptom1->currentText(), "9");

        if( diag_code.isEmpty() || symp_code.isEmpty())
        {
            //诊断为空，返回
            qDebug()<<"中医诊断和证候："
                   <<ui->cbb_tr_diag1->currentText()
                  <<" , "
                 <<ui->cbb_tr_symptom1->currentText()
                <<" : "<<diag_code<<","<<symp_code<<"\n";
        }
        else
        {
            sq = " select tr_similar_syndrom,tr_treatment"
                 " from com_diag_med_tr where tr_diag_code = '" + diag_code + "'";
            sq += " and  tr_symptom_code = '" + symp_code + "'";
            sq += " and dept_code = '" + pub::dp_code + "'";

            qDebug()<<"根据中医诊断代码提取补充信息：";
            qDebug()<<sq<<"\n";
            qrmt->exec(sq);

            if(qrmt->next())
            {
                //中医类证鉴别
                ui->pt_similar_syndrom->setPlainText(qrmt->value("tr_similar_syndrom").toString());

                //中医治则
                ui->pt_treat_tr->setPlainText(qrmt->value("tr_treatment").toString());
            }
        }
    }

    //检验相关
    //on_tabWidget_currentChanged(2);
    display_aux_check();

    //随访相关信息
    sq = "select wx_name, book_date from ys_bz_e_call where clinic_code = '" + mpPatientInfo["clinic_code"] + "'";
    qrm->exec(sq);
    if(qrm->next())
    {
        ui->le_wx_name->setText(qrm->value(0).toString());
        QDate dt = qrm->value(1).toDate();
        ui->le_next_call->setText(QString::number(QDate::currentDate().daysTo(dt)));
    }

    ui->rbIn->setChecked(true);

    //if(ui->deRegDate->date().addDays(3) >= QDate::currentDate()
    //QDateTime dt = QDateTime::fromString( mpPatientInfo["reg_date"], "yyyy-MM-dd hh:mm:ss");
    //dt = dt.addDays(3);

    //dt >= QDateTime::currentDateTime()

    if( ui->tab_recipe_new->isEnabled()
            &&  mpPatientInfo["pact_code"] == "2" )
    {
        //三日内医保患者可进行相关查询
        ui->rbOut->setVisible(true);
        ui->rbOut->setChecked(true);
        //ui->pbCheck3101->setEnabled(true);
        sq = "select mdtrt_id,insuplc_admdvs from fin_ipr_siinmaininfo "
             " where inpatient_no = '" +mpPatientInfo["clinic_code"] + "' ";
        qrot->exec(sq);
        qrot->next();
        mpPatientInfo.insert("mdtrt_id", qrot->value(0).toString());
        mpPatientInfo.insert("poolarea", qrot->value(1).toString());
    }
    else
    {
        ui->rbOut->setVisible(false);
        //ui->pbCheck3101->setEnabled(false);
    }

    //查询是否已经保存过本次门诊病志
    sq = "select atinc from ys_bz_e_rec where clinic_code = '" + mpPatientInfo["clinic_code"] + "'";
    qrm->exec(sq);
    if(qrm->next())
    {
        //保存过门诊病志，不再查询医保历史处方，只查询本院，且首页进入基础病志
        qDebug()<<"保存过本次门诊病志，不再查询医保历史处方，只查询本院，且首页进入基础病志\n";
        ui->rbOut->setChecked(false);
        ui->tabWidget->setCurrentIndex(1);
    }
    else
    {
        qDebug()<<"本次门诊病志尚未保存\n";
    }

    on_pbHistory_clicked();

    dlgDelay->setNeedClose(true);
    dlgDelay->closeWindow();

}

void Form_ys_bzgl::getRegDateRecipe()
{
    dlgDelay->setText("正在提取挂号当日处方数据。。。");
    dlgDelay->setModal(true);
    dlgDelay->setNeedClose(false);
    dlgDelay->show();

    qApp->processEvents();

    ui->pbRemoveUncharge->setEnabled(false);//处方项目撤销按钮

    sq = "select CASE WHEN clinicotherdiag2_name IS NOT NULL THEN"
         "     CONCAT ( CONCAT ((CASE WHEN clinicotherdiag1_name IS NOT NULL THEN CONCAT ("
         "     CONCAT (clinicdiag_name, '，'),clinicotherdiag1_name)ELSE clinicdiag_name"
         "     END),'，'),clinicotherdiag2_name) ELSE ( CASE WHEN clinicotherdiag1_name IS NOT NULL "
         "     THEN CONCAT ( CONCAT (clinicdiag_name, '，'), clinicotherdiag1_name)ELSE clinicdiag_name END ) END 诊断 ,"  //0
         " reci.item_name 项目名称, reci.qty 数量, reci.item_unit 单位, reci.unit_price 价格, "//1-4
         " reci.own_cost 金额, reci.doct_name 医生, " //5-6
         " case when reci.status = '0' then '未付' else "
         "     (case when reci.status = '3' then '作废' else "
         "     (case when reci.status = '4' then '撤销' else '正常' end ) end ) end  标志, "  //7
         " reci.status, reci.sequence_no , reci.recipe_no ,"  //8-10
         " fee.days 天数, case when insu.mo_order is null then '%1' else '现金' end 费别 ,"//11-12
         " reci.item_code, reci.oper_date" //13-14
         " from met_ord_recipedetail reci "
         " left join fin_opb_insu_cash insu on insu.mo_order = reci.sequence_no"
         " join fin_opb_feedetail fee on fee.mo_order = reci.sequence_no"
         " where reci.clinic_code = '" + mpPatientInfo["clinic_code"] + "'";

    if(!ui->ckbDisplayCancel->isChecked())
    {
        sq += " and reci.status not in ('3','4') ";
    }

    sq += "order by reci.recipe_no, reci.sort_id";
    sq = sq.arg(mpPatientInfo["pact_name"]);
    qDebug()<<"读取挂号日期处方："<<sq;
    mdRecipe->setQuery(sq, pub::db_o);
    ui->tvRecipe->setModel(mdRecipe);

    double payed , unpayed;
    QString status;
    payed = unpayed = 0;
    recipe_list_5465.clear();

    for(int i = 0 ; i< mdRecipe->rowCount(); i++)
    {
        recipe_list_5465 << mdRecipe->record(i).value(10).toString();

        status = mdRecipe->record(i).value(8).toString();
        if( status == "4" || status == "3")
        {
            //撤销, 作废
            continue;
        }
        else if(status == "0")
        {
            unpayed += mdRecipe->record(i).value(5).toDouble();
        }
        else
        {
            payed += mdRecipe->record(i).value(5).toDouble();
        }

    }

    ui->lePayed->setText(QString::asprintf("%.2f", payed));
    ui->leUnPayed->setText(QString::asprintf("%.2f", unpayed));

    dlgDelay->setNeedClose(true);
    dlgDelay->closeWindow();
    return;

}

void Form_ys_bzgl::on_pbHistory_clicked()
{

    if(remoteQuery)
    {
        QMessageBox::warning(this, "注意", "正在进行远程查询，请稍候......");
        qApp->processEvents();
        return;
    }

    if(ui->rbIn->isChecked())
    {
        localHistory(mpPatientInfo["card_no"]);
    }
    else
    {
        if(ui->lePatientType->text() == "现金")
        {
            ui->rbIn->setChecked(true);
            return;
        }

        remoteQuery = true;

        QJsonObject in, inpu;

        inpu.insert("psn_name", mpPatientInfo["name"]);//人员姓名	字符型	50		Y
        inpu.insert("certno", mpPatientInfo["idenno"]);//身份证号码	字符型	50		Y
        inpu.insert("chfpdr_code", ybysdm);//医师编号	字符型	30		Y
        inpu.insert("mdtrt_id", mpPatientInfo["mdtrt_id"]);//就诊id	字符型	30		Y

        in.insert("data",inpu);

        dlgDelay->setText("从医保获取数据。。。");
        dlgDelay->setModal(true);
        dlgDelay->setNeedClose(false);
        dlgDelay->show();

        qApp->processEvents();

        bool ret_5960 = call_5960(in);

        last_hospital_info = "";

        if(!ret_5960)
        {
            //5960失败，没必要尝试5283
            dlgDelay->setNeedClose(true);
            dlgDelay->closeWindow();

            remoteQuery = false;
            return;
        }


        // 5283 信息
        sq = "select psn_no from fin_ipr_siinmaininfo "
             " where inpatient_no = '" + mpPatientInfo["clinic_code"] + "' ";

        qDebug()<<"提取　psn_no : "<<sq;

        qro->exec(sq);
        qro->next();

        QJsonObject jsonRet;    //医保交易返回的Json数据
        QString info;   //如果返回错误，保存错误信息

        QJsonObject in5283, inpu5283;

        inpu5283.insert("psn_no", qro->value(0).toString());//人员编号	字符型	50		Y

        in5283.insert("data",inpu5283);


        if( ! pub::call_business("5283", in5283, info, jsonRet, "", true ,
                                 manager, request, mpPatientInfo["clinic_code"]))
        {
            QMessageBox::warning(this, "注意", info);
            //return;
        }
        else
        {
            //QJsonObject ret = jsonRet.value("output").toObject().value("result").toObject();
            QJsonArray ret_a = jsonRet.value("output").toObject().value("result").toArray();
            QJsonObject ret = ret_a[0].toObject();

            if(!ret.value("fixmedins_code").toString().isEmpty())
            {
                //QDate dt;
                last_hospital_info = "\n最后一次入院信息 : \n";
                last_hospital_info += "机构编号:" + ret.value("fixmedins_code").toString() + "\n";
                last_hospital_info += "机构名称:" + ret.value("fixmedins_name").toString() + "\n";
                //dt = ret.value("begndate").to .toDate();
                last_hospital_info += "入院时间:" + ret.value("begndate").toString() + "\n";
                last_hospital_info += "出院时间:" + ret.value("enddate").toString();
            }
        }

        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();

        remoteQuery = false;
    }

}

bool Form_ys_bzgl::call_5960(QJsonObject &inpu)
{
    // root -- > input -- > data
    // inpu -> inpud.data, inpud-> in.input

    QJsonObject jsonRet;    //医保交易返回的Json数据
    QString info;   //如果返回错误，保存错误信息

    if( ! pub::call_business("5960", inpu, info, jsonRet, "", true ,
                             manager, request, mpPatientInfo["clinic_code"]))
    {
        QMessageBox::warning(this, "注意", info);
        return false;
    }

    //qDebug()<<"jsonRet"<<jsonRet;

    QJsonArray ret = jsonRet.value("output").toObject().value("feelistinfo").toArray();


    if(ret.size() == 0)
    {
        QMessageBox::warning(this, "注意", "查询不到3个月内的医保记录。");
        return true;
    }
    qro->exec("delete from med_history");
    for(int i = 0; i< ret.size(); i++){
        sq = "insert into med_history (fee_ocur_time, hilist_name, spec, cnt, setl_flag,memo) values(";
        sq += "to_date('"+ret[i].toObject().value("fee_ocur_time").toString()+"','yyyy-mm-dd hh24:mi:ss'),";
        sq += "'"+ret[i].toObject().value("hilist_name").toString()+"',";
        sq += "'"+ret[i].toObject().value("spec").toString()+"',";
        sq += QString::asprintf("%.2f", ret[i].toObject().value("cnt").toDouble())+",";
        sq += "'"+ret[i].toObject().value("setl_falg").toString()+"',";
        QString memo;
        if(!ret[i].toObject().value("sin_dos_dscr").toString().isEmpty()){
            memo += "单次剂量：" + ret[i].toObject().value("sin_dos_dscr").toString() + "\n";
        }
        if(!ret[i].toObject().value("used_frqu_dscr").toString().isEmpty()){
            memo += "使用频次：" + ret[i].toObject().value("used_frqu_dscr").toString() + "\n";
        }
        if(!ret[i].toObject().value("drug_unit").toString().isEmpty()){
            memo += "最小包数量：" + ret[i].toObject().value("drug_unit").toString() + "\n";
        }
        if(!ret[i].toObject().value("fixmedins_type").toString().isEmpty()){
            memo += "机构标识：" + ret[i].toObject().value("fixmedins_type").toString() + "\n";
        }
        if(!ret[i].toObject().value("drug_used_prd_days").toString().isEmpty()){
            memo += "可用天数：" + ret[i].toObject().value("drug_used_prd_days").toString() + "\n";
        }
        if(!ret[i].toObject().value("drug_used_rem_days").toString().isEmpty()){
            memo += "剩余天数：" + ret[i].toObject().value("drug_used_rem_days").toString() + "\n";
        }
        if(!ret[i].toObject().value("next_drug_date").toString().isEmpty()){
            memo += "下次开药日期：" + ret[i].toObject().value("next_drug_date").toString() ;
        }

        sq += "'" + memo + "')";
        qro->exec(sq);

        qDebug()<<sq;
    }
    sq = "select to_char(fee_ocur_time,'yyyy-mm-dd') 时间 ,hilist_name 项目名称, spec 规格, "
         "cnt 数量, setl_flag 结算 , memo"
         " from med_history order by fee_ocur_time ";

    if(ui->cbHisOrder->isChecked())
    {
        sq += " desc ";
    }
    mdHist->setQuery(sq, pub::db_o);
    ui->tvHistory->setModel(mdHist);
    pub::setColumnWidth(ui->tvHistory, "0.2^0.3^0.2^0.1^0.1", ui->tvHistory->width(), 8);

    return true;
}

void Form_ys_bzgl::localHistory(QString bzh)
{
    qro->exec("delete from med_history");

    sq = "insert into med_history (fee_ocur_time  ,hilist_name, spec, cnt, setl_flag,doct_name, "
         " clinic_code,diag, mo_order, fee_type)  ";
    sq += " select OPER_DATE,ITEM_NAME,SPECS,QTY,status,DOCT_NAME, clinic_code, "
          " CASE WHEN clinicotherdiag2_name IS NOT NULL THEN"
          "     CONCAT ( CONCAT ((CASE WHEN clinicotherdiag1_name IS NOT NULL THEN CONCAT ("
          "     CONCAT (clinicdiag_name, '，'),clinicotherdiag1_name)ELSE clinicdiag_name"
          "     END),'，'),clinicotherdiag2_name) ELSE ( CASE WHEN clinicotherdiag1_name IS NOT NULL "
          "     THEN CONCAT ( CONCAT (clinicdiag_name, '，'), clinicotherdiag1_name)ELSE clinicdiag_name END ) END 诊断 ,"
          " sequence_no,''";
    sq += " from met_ord_recipedetail where card_no='" + bzh + "' ";//order by sort_id";

    if(!qro->exec(sq))
    {
        QMessageBox::warning(this, "注意", "提取处方历史数据发生错误！");
        qDebug()<<sq;
    }

    sq = "insert into med_history "
         " (fee_ocur_time  ,hilist_name, spec, cnt, setl_flag,doct_name, clinic_code,diag,mo_order,fee_type)  "
         " select OPER_DATE,CONCAT( CONCAT(pact_name,' : ' ),DEPT_NAME) ,'-',1,TRANS_TYPE + 1 ,'-',"
         " clinic_code, '-','no_mo_oder',''";
    sq += " from FIN_OPR_REGISTER where card_no='" + bzh + "' ";//order by sort_id";

    if(!qro->exec(sq))
    {
        QMessageBox::warning(this, "注意", "提取挂号历史数据发生错误！");
        qDebug()<<sq;
    }

    //按挂号时的费用类别填充
    QString codes = "'clinic_code'";
    sq = " select pact_name, clinic_code from FIN_OPR_REGISTER where card_no='" + bzh + "' ";
    qro->exec(sq);
    while(qro->next())
    {
        QString fee_type = qro->value("pact_name").toString();
        QString clinic_code = qro->value("clinic_code").toString();
        codes.append(",'" + clinic_code + "'");

        sq = " update med_history set "
             " fee_type = '" + fee_type + "' where clinic_code = '" + clinic_code + "'";
        qrot->exec(sq);
    }

    //按实际收费费用类别修正
    sq = " select mo_order from fin_opb_insu_cash where clinic_code in (" + codes + ")";
    qro->exec(sq);
    while(qro->next())
    {
        QString mo_order = qro->value(0).toString();
        sq = " update med_history set fee_type = '现金' "
             " where mo_order = '" + mo_order + "'";
        qrot->exec(sq);
    }

    sq = "select to_char(fee_ocur_time,'yyyy-mm-dd') 时间, diag 诊断 ,hilist_name 项目名称,"
         " spec 规格, cnt 数量, doct_name 医生, "
         "  case when setl_flag = '0' then '未付' else "
         " (case when setl_flag = '3' then '作废' else "
         " (case when setl_flag = '4' then '撤销' else '正常' end ) end ) end  标志 ,"
         "  clinic_code , fee_type 费别"
         " from med_history order by fee_ocur_time ";
    if(ui->cbHisOrder->isChecked())
    {
        sq += " desc ";
    }
    //Debug()<<sq;
    mdHist->setQuery(sq, pub::db_o);
    ui->tvHistory->setModel(mdHist);
    pub::setColumnWidth(ui->tvHistory, "0.13^0.15^0.18^0.1^0.05^0.1^0.06^0^0.1", ui->tvHistory->width(), 10);

}

void Form_ys_bzgl::on_rbIn_clicked()
{
    if(remoteQuery)
    {
        QMessageBox::warning(this, "注意", "正在进行远程查询，请稍候......");
        ui->rbOut->setChecked(true);
        qApp->processEvents();
        return;
    }
    mdHist->setQuery("");
}

void Form_ys_bzgl::on_rbOut_clicked()
{
    if(remoteQuery)
    {
        return;
    }
    mdHist->setQuery("");
    //on_pbHistory_clicked();
}

void Form_ys_bzgl::fillCombo(QComboBox *cbb,
                             QString sq ,
                             int ind, //填充之后的默认选项
                             bool clear_before_fill , //填充之前是否清空
                             QMap<QString, QString> *mp)//是否保存
{

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "检索 comboBox 记录失败！\nerrmsg : "
                                 + qrm->lastError().text()+"\nsql : "+sq);
        return;
    }

    if(clear_before_fill)
    {
        cbb->clear();
    }

    while(qrm->next())
    {
        cbb->addItem(qrm->value(0).toString());
        if(mp != NULL)
        {
            *mp->insert(qrm->value(0).toString(),qrm->value(1).toString());
        }
    }

    cbb->setCurrentIndex(ind);

}

void Form_ys_bzgl::on_cbbGms_currentTextChanged(const QString &arg1)
{
    if(!initialFinished)    return; //界面初始化未完成

    if(arg1.isEmpty()) return;
    ui->leGms->insert(arg1);

    ui->cbbGms->setCurrentIndex(-1);

}

void Form_ys_bzgl::on_cbbJws_currentTextChanged(const QString &arg1)
{
    if(!initialFinished)    return; //界面初始化未完成

    if(arg1.isEmpty()) return;

    ui->leJws->insert(arg1);

    ui->cbbJws->setCurrentIndex(-1);

}

void Form_ys_bzgl::on_cbbBzmb_currentIndexChanged(const QString &arg1)
{
    // 病志模板
    if(!initialFinished) return; //界面初始化未完成
    if(arg1.isEmpty()) return;

    sq = "select hzzs,jws,xbs,tgjc,yz,gms ,xbs_tr,tgjc_tr,zybz,zljl "
         " from ys_bz_e_model where mblx = 'bz' ";
    sq += " and mbmc = '" + arg1 + "' and dept_code = '" + pub::dp_code + "'";

    qDebug()<<"模板名称变化："<<sq;
    qrm->exec(sq);
    qrm->next();

    ui->leHzzs->setText(qrm->value("hzzs").toString());
    ui->leJws->setText(qrm->value("jws").toString());
    ui->pt_current_symp->setPlainText(qrm->value("xbs").toString());
    ui->leGms->setText(qrm->value("gms").toString());
    ui->pt_medical_advice->setPlainText(qrm->value("yz").toString());
    ui->pt_body_check->setPlainText(qrm->value("tgjc").toString());
    //ui->pt_current_symp_tr->setPlainText(qrm->value("xbs_tr").toString());
    ui->pt_person_history->setPlainText(qrm->value("person_hist").toString());
    ui->le_menstr->setText(qrm->value("menstr_hist").toString());
    ui->pt_family_history->setPlainText(qrm->value("family_hist").toString());
    ui->pt_treat_tr->setPlainText(qrm->value("treat").toString());
    ui->pt_similar_syndrom->setPlainText(qrm->value("similar").toString());

    ui->pt_body_check_tr->setPlainText(qrm->value("tgjc_tr").toString());
    ui->pt_tr_diag->setPlainText(qrm->value("zybz").toString());
    ui->cbb_conclusion->setCurrentText(qrm->value("zljl").toString());
    if(ui->cbb_conclusion->currentText().isEmpty())
    {
        ui->cbb_conclusion->setCurrentIndex(0);
    }

}

void Form_ys_bzgl::on_pbModelDelete_clicked()
{
    QString mb = ui->cbbBzmb->currentText().trimmed();
    if(mb.isEmpty())
    {
        QMessageBox::information(this, "注意", "未指定模板名称！");
        return;
    }

    QMessageBox:: StandardButton result= QMessageBox::warning(this, "注意", "确定要删除指定名称的模板？",QMessageBox::Yes|QMessageBox::No);
    if(result == QMessageBox::No)
    {
        return;
    }

    sq="delete from ys_bz_e_model where mblx='bz' and mbmc='"+mb+"' and dept_code = '" + pub::dp_code + "'";
    qrm->exec(sq);

    QMessageBox::information(this, "注意", "删除完成！");
    ui->cbbBzmb->setCurrentIndex(-1);

}

void Form_ys_bzgl::on_pbModeSave_clicked()
{
    //修改病志模板
    QString mb = ui->cbbBzmb->currentText().trimmed();  //
    if(mb.isEmpty())
    {
        return;
    }
    sq = "select mbmc from ys_bz_e_model where mblx = 'bz' and mbmc = '";
    sq += mb + "' and dept_code = '" + pub::dp_code + "'";

    qrm->exec(sq);
    if(qrm->next())
    {
        QMessageBox:: StandardButton result;
        result = QMessageBox::warning(NULL, "注意", "此名称模板已经存在，是否覆盖？",QMessageBox::Yes|QMessageBox::No);
        if(result == QMessageBox::No)
        {
            return;
        }
        else
        {
            sq = "update ys_bz_e_model set ";
            sq += "hzzs = '"+ui->leHzzs->text()+"',";
            sq += "xbs = '"+ui->pt_current_symp->toPlainText()+"' , ";
            sq += "jws ='"+ui->leJws->text()+"',";
            sq += "gms ='"+ui->leGms->text()+"',";
            sq += "tgjc ='"+ui->pt_body_check->toPlainText()+"',";
            sq += "person_hist ='"+ui->pt_person_history->toPlainText()+"',";

            sq += "menstr_hist ='"+ui->le_menstr->text()+"',";
            sq += "family_hist ='"+ui->pt_family_history->toPlainText()+"',";
            sq += "treat ='"+ui->pt_treat_tr->toPlainText()+"',";
            sq += "similar ='"+ui->pt_similar_syndrom->toPlainText()+"',";

            sq += "tgjc_tr ='"+ui->pt_body_check_tr->toPlainText()+"',";
            sq += "zybz ='"+ui->pt_tr_diag->toPlainText()+"',";
            sq += "zljl ='"+ui->cbb_conclusion->currentText()+"',";
            sq += "yz = '" + ui->pt_medical_advice->toPlainText() + "'";
            sq += " where dept_code = '" + pub::dp_code + "' and mbmc ='" + mb + "'";
        }
    }
    else
    {
        sq = "insert into ys_bz_e_model "
             "(ks, mblx, dept_code, mbmc,"
             "hzzs,"
             "xbs,"
             "jws,"
             "gms,"
             "tgjc,"
             "yz,"
             "person_hist,"
                "menstr_hist,"
                "family_hist,"
                "treat,"
                "similar,"
             "tgjc_tr,"
             "zybz,"
             "zljl) "
             "values(";
        sq += "'ks','bz','"+pub::dp_code+"','"+mb+"','";
        sq += ui->leHzzs->text()+"','"; //hzzs
        sq += ui->pt_current_symp->toPlainText()+"','";//xbs
        sq += ui->leJws->text()+"','";//jws
        sq += ui->leGms->text()+"','";//gms
        sq += ui->pt_body_check->toPlainText()+"','";//tgjc
        sq += ui->pt_medical_advice->toPlainText() + "','";//yz
        sq += ui->pt_person_history->toPlainText()+"','";//
        sq += ui->le_menstr->text()+"','";//
        sq += ui->pt_family_history->toPlainText()+"','";//
        sq += ui->pt_treat_tr->toPlainText()+"','";//
        sq += ui->pt_similar_syndrom->toPlainText()+"','";//
        sq += ui->pt_body_check_tr->toPlainText()+"','";//tgjc_tr
        sq += ui->pt_tr_diag->toPlainText()+"','";
        sq += ui->cbb_conclusion->currentText()+"')";

    }

    qDebug()<<"模版变更："<<sq;

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "保存模板数据失败！\nerrmsg : "
                                 + qrm->lastError().text());
    }
    else
    {
        QMessageBox::information(this, "注意", "模板 \""+ mb +"\" 保存成功。");
    }

}


bool Form_ys_bzgl::undrug_check()
{

    //非药品项目合理性校验

    qDebug()<<"\n\n undrug_check()非药品项目合理性校验\n";

    QSqlQuery * qr_tmp = new QSqlQuery(pub::db_m);
    QString pact_mode;

    if(ui->rb_reci_ct_insu->isChecked())
    {
        pact_mode = "医保";       //医保
    }
    else
    {
        pact_mode = "现金";       //现金
    }

    //处方临时表中的非药品项目
    sq = "select reci.item_code , reci.diag1c, reci.diag2c, reci.diag3c, reci.freq_days,"
         " reci.base_dose, reci.pack_qty, reci.once_dose, reci.qty, "
         " reci.item_name, reci.item_type, reci.qty_unit ,reci.recipe_days, "
         " reci.diag1, reci.diag2, reci.diag3, "
         " reci.dose_model_code, reci.usages, reci.dose_unit, reci.fee_code ,"
         " icpc.item_name"
         " from tmp_recipe reci"
         " left join com_dict_icpc icpc on icpc.item_code = reci.item_code "
         "      and icpc.valid_flag = '1' and icpc.type = '1' "
         " where reci.item_type in('2','3') order by reci.seq";
    qrm->exec(sq);

    qDebug()<<"提取处方临时表中的非药品项目"<<sq<<"\n";

    QString fee_code, item_name, item_code;
    QString item_names = "'item_name'";
    while(qrm->next())
    {

        item_name = qrm->value("reci.item_name").toString();
        item_code = qrm->value("item_code").toString();
        fee_code = qrm->value("fee_code").toString();
        item_names += ",'" + qrm->value("icpc.item_name").toString() + "'";
        item_names += ",'" + item_name + "'";

        if(fee_code.isEmpty())
        {
            QMessageBox::information(this, "注意", item_name + " 在 fin_com_undruginfo 中找不到基础信息！");
            delete qr_tmp;
            return false;
        }

        //限量标准使用顺序：
        // 1 item_name + dept_code
        // 2 item_name + 默认
        // 3 fee_type + dept_code
        // 4 fee_type  + 默认

        sq = " select days_count_single, days_count_current, 10 ord "
             " from reci_ck_days"
             " where item_name = '%4' "
             " and dept_code = '%2' and pact_type ='%3'"
             " union "
             " select days_count_single, days_count_current, 20 ord "
             " from reci_ck_days"
             " where item_name = '%4' "
             " and dept_code = '默认' and pact_type ='%3'"
             " union "
             " select days_count_single, days_count_current, 30 ord "
             " from reci_ck_days"
             " where fee_type = (select name from com_dict_com where dic_type = 'MINFEE' and code = '%1') "
             " and dept_code = '%2' and pact_type ='%3'"
             " union "
             " select days_count_single, days_count_current, 40 ord "
             " from reci_ck_days"
             " where fee_type = (select name from com_dict_com where dic_type = 'MINFEE' and code = '%1')"
             " and dept_code = '默认' and pact_type ='%3'"
             " order by ord";
        sq = sq.arg(fee_code).arg(pub::dp_name).arg(pact_mode).arg(item_name);

        qDebug()<<"检索非药品处方限量 : "<<sq<<"\n";
        qr_tmp->exec(sq);

        if(!qr_tmp->next())
        {
            qDebug()<<item_name + "未找到处方限量标准。\n";
            QMessageBox::warning(this, "注意", item_name + " 找不到处方限量标准！");
            return false;
        }
        else
        {

            int days_count_single_u = qr_tmp->value(0).toInt();
            int days_count_current_u = qr_tmp->value(1).toInt();

            qDebug()<<"计算本次处方是否超限量\n";
            int all_days = qrm->value("qty").toDouble();

            //累计本日总数量是否超限
            qDebug()<<"计算本日总数量是否超限\n";
            sq = "select sum(qty) from fin_opb_feedetail where card_no = '";
            sq += mpPatientInfo["card_no"] + "' and item_code = '" + item_code + "'";
            sq += " and oper_date > trunc(sysdate)";
            sq += " and cancel_flag = '1' "; //and pay_flag = '1'

            qro->exec(sq);
            qDebug()<<sq<<"\n";

            qro->next();
            if(qro->value(0).isValid())
            {
                all_days += qro->value(0).toInt();
            }

            if(all_days > days_count_single_u ) //天数超限* + days_count_current_u
            {

                QMessageBox::information(this, "注意", item_name + " 当日处方累计数量为 " + QString::number(all_days) + " 次，超过处方限量！");
                QString err_msg = item_name + ", " + QString::number(all_days) + " 次";
                qDebug()<<"本次处方超限量"<<err_msg<<"\n";
                save_recipe_error("单次处方超量", err_msg);
                delete qr_tmp;
                return false;
            }

            qDebug()<<"计算非药品治疗间隔是否超限\n";
            sq = "select max(oper_date) from fin_opb_feedetail where card_no = '";
            sq += mpPatientInfo["card_no"] + "' and item_code = '" + item_code + "'";
            sq += " and oper_date < trunc(sysdate)";
            sq += " and cancel_flag = '1' and pay_flag = '1'";
            qDebug()<<sq<<"\n";

            qro->exec(sq);
            qro->next();
            //包含计算字段，无法用 next(),或者isValid()进行判断
            if(!qro->value(0).toString().isEmpty())
            {
                QDate cur = QDate::currentDate();
                QDate reci = qro->value(0).toDate();

                int days = reci.daysTo(cur);

                if(days < days_count_current_u ) //间隔不足
                {
                    QMessageBox::information(this, "注意", item_name + " 处方间隔天数为 " + QString::number(days) + " ，不符合处方规定！");
                    QString err_msg = item_name + ", " + QString::number(all_days) + " 次";
                    qDebug()<<"处方间隔天数"<<err_msg<<"\n";
                    save_recipe_error("处方间隔天数", err_msg);
                    delete qr_tmp;
                    return false;
                }
            }


        }
    }
    //本日已经开具项目
    sq = "select distinct item_name from fin_opb_feedetail where clinic_code = '";
    sq += mpPatientInfo["clinic_code"] + "' ";//and item_code = '" + item_code + "'";
    sq += " and oper_date > trunc(sysdate)";
    sq += " and cancel_flag = '1' "; //and pay_flag = '1'
    qro->exec(sq);
    qDebug()<<"提取本日已经开具项目"<<sq<<"\n";
    while(qro->next())
    {
        item_names += ",'" + qro->value(0).toString() + "'";
    }

    sq = " select count(conflict_type), conf_name, conflict_type "
         " from reci_ck_drug_conflict "
         " where drug_name in(" + item_names + ") group by conf_name,conflict_type";
    qrm->exec(sq);
    qDebug()<<"核查项目联合应用冲突："<<sq<<"\n";
    while(qrm->next())
    {
        if(qrm->value(0).toInt() > 1)
        {
            QMessageBox::information(this, "注意", "触发项目联合冲突限制 "
                                     + qrm->value(1).toString() +", " + qrm->value(2).toString());

            QString err_msg = qrm->value(1).toString() +", " + qrm->value(2).toString();
            save_recipe_error("项目联合冲突", err_msg);

            delete qr_tmp;

            return false;

        }
    }

    //诊断是否存在性别冲突
    QString diags = "'" + ui->cbbDiag1->currentText() + "','";
    diags += ui->cbbDiag2->currentText() + "','";
    diags += ui->cbbDiag3->currentText() + "'";

    sq = "select gend , diag_name from reci_ck_diag_gend "
         " where diag_name in (" + item_names + ") ";
    qrm->exec(sq);
    qDebug()<<"性别冲突检查："<<sq<<"\n";
    while(qrm->next())
    {
        QString gd = qrm->value(0).toString();
        if( gd != "不限" && gd != mpPatientInfo["gender"] )
        {
            QMessageBox::information(this, "注意", "处方项目与性别不符 ！ ");

            QString err_msg = qrm->value(1).toString() +" 限制性别为 " + qrm->value(0).toString();
            save_recipe_error("处方项目与性别不符", err_msg);
            delete qr_tmp;
            return false;
        }
    }

    qDebug()<<"非药品项目检查结束。\n";
    delete qr_tmp;
    return true;
}


bool Form_ys_bzgl::drugCheck()
{
    qDebug()<<"\n\ndrugCheck()\n";
    //提取处方限量数据
    QString pact_mode;
    if(ui->rb_reci_ct_insu->isChecked())
    {
        pact_mode = "医保";       //医保
    }
    else
    {
        pact_mode = "现金";       //现金
    }

    //sq = " select days_count_single, days_count_current "
    //     " from reci_ck_days"
    //     " where reci_type = 'drug' and pact_type ='" + pact_mode + "'";


    //处方临时表中的药品项目
    sq = "select item_code , diag1c, diag2c, diag3c, freq_days,"
         " base_dose, pack_qty, once_dose, qty, "
         "item_name, item_type, qty_unit ,recipe_days, diag1, diag2, diag3, "
         " dose_model_code, usages, dose_unit ,fee_code"
         " from tmp_recipe "
         " where item_type in('1','4') order by seq";
    qrmt->exec(sq);

    qDebug()<<"处方临时表中的药品项目"<<sq<<"\n";

    QString item, diag1, diag2, diag3,item_name, type, fee_code;
    QString drug_names = "'drug_names'";
    while(qrmt->next())
    {
        type = qrmt->value("item_type").toString();
        item_name = qrmt->value("item_name").toString();
        fee_code = qrmt->value("fee_code").toString();

        if(qrmt->value("qty_unit").toString().isEmpty())
        {
            QMessageBox::information(this, "注意", item_name + " 数量单位为空！");
            return false;
        }
        if(type == "1") //西药中成药
        {

            item = qrmt->value(0).toString();       //item_code

            sq = " select days_count_single, days_count_current, 10 ord "
                 " from reci_ck_days"
                 " where item_name = '%4' "
                 " and dept_code = '%2' and pact_type ='%3'"
                 " union "
                 " select days_count_single, days_count_current, 20 ord "
                 " from reci_ck_days"
                 " where item_name = '%4' "
                 " and dept_code = '默认' and pact_type ='%3'"
                 " union "
                 " select days_count_single, days_count_current, 30 ord "
                 " from reci_ck_days"
                 " where fee_type = (select name from com_dict_com where dic_type = 'MINFEE' and code = '%1') "
                 " and dept_code = '%2' and pact_type ='%3'"
                 " union "
                 " select days_count_single, days_count_current, 40 ord "
                 " from reci_ck_days"
                 " where fee_type = (select name from com_dict_com where dic_type = 'MINFEE' and code = '%1')"
                 " and dept_code = '默认' and pact_type ='%3'"
                 " order by ord";
            sq = sq.arg(fee_code).arg(pub::dp_name).arg(pact_mode).arg(item_name);

            qDebug()<<"检索药品处方限量 : "<<sq<<"\n";
            qrm->exec(sq);
            if(!qrm->next())
            {
                qDebug()<<item_name + "未找到处方限量标准。\n";
                QMessageBox::warning(this, "注意", item_name + " 找不到处方限量标准！");
                return false;
            }

            QString days_count_single = qrm->value(0).toString();
            QString days_count_current = qrm->value(1).toString();

            //本次处方是否超限量
            qDebug()<<"计算本次处方是否超限量\n";
            double all_days , pack_days;   //总天数， 每包装可用天数
            pack_days = qrmt->value("base_dose").toDouble() * qrmt->value("pack_qty").toDouble()
                    / qrmt->value("once_dose").toDouble() / qrmt->value("freq_days").toDouble() ;
            all_days = pack_days * qrmt->value("qty").toDouble();

            if(all_days - pack_days >= days_count_single.toInt()) //减少一个包装之后天数仍然超限
            {

                QMessageBox::information(this, "注意", item_name + "用量为 " + QString::asprintf("%.0f", all_days) + " 天，超过处方限量！");
                QString err_msg = item_name + ", " + QString::asprintf("%.0f", all_days) + " 天";

                qDebug()<<"本次处方超限量"<<err_msg<<"\n";
                save_recipe_error("单次处方超量", err_msg);

                return false;
            }

            sq = "update tmp_recipe set recipe_days = round(" + QString::number(all_days) + ") ";
            sq += " where item_code = '" + item + "'";
            qrm->exec(sq);


            QString msg;    //提示显示信息

            //计算历史开药数据
            qDebug()<<"计算历史开药数据\n";
            sq = " select fee.days, fee.oper_date "
                 " from fin_opb_feedetail fee "
                 " where fee.card_no = '" + mpPatientInfo["card_no"] + "'";
            sq += " and fee.item_code = '" + item + "'";
            sq += " and fee.oper_date > sysdate - ("
                    + days_count_single + " * " +  days_count_current + ")";
            sq += " and fee.cancel_flag = '1' ";

            //处方项目关联的挂号记录状态应为有效
            sq += " and (select reg.valid_flag from fin_opr_register reg"
                  "      where reg.clinic_code = fee.clinic_code"
                  "      and rownum = 1 ) = '1' ";

            sq += " order by fee.oper_date desc ";
            qro->exec(sq);
            qDebug()<<"检索三个处方周期累计用量："<<sq<<"\n";

            int count = 0;
            int maxCount = 0;  //最大可用处方天数
            int realDays = 0;   //处方日期至当前日期的天数
            QDate curD, RecipeD,maxD;

            curD = QDate::currentDate();
            while(qro->next())
            {
                RecipeD = qro->value(1).toDate();
                count += qro->value(0).toInt();
                realDays = RecipeD.daysTo(curD);

                if(count - realDays > maxCount)
                {
                    //保存最大可用处方天数的处方日期
                    maxCount = count - realDays;
                    maxD = RecipeD;
                }
            }

            //周期累计 ，是否超限量
            if( qrmt->value("qty").toInt() == 1 && maxCount == 0)
            {
                //药品数量为 1， 且无历史累计数据
                qDebug()<< "药品数量为 1 且无历史累计数据, 不需要进行累计限量计算！";
            }
            else
            {
                // 之前余量 + 本日 = 当前患者手中最大可用数量 ，是否超？
                if(maxCount + all_days > days_count_single.toInt() * days_count_current.toInt())
                {

                    msg = "本次开药后患者 "+item_name+" 应有 " + QString::number(maxCount + all_days) + " 天用量，超出最大合理范围！";

                    QMessageBox::information(this, "注意", msg);

                    QString err_msg = "本次开药后 "+item_name+" 用量达到 " + QString::number(maxCount + all_days) + " 天";

                    qDebug()<<"累计处方超限量，"<<err_msg<<"\n";
                    save_recipe_error("处方累计超量", err_msg);

                    return false;
                }
            }

            //诊断与用药是否相符
            qDebug()<<"诊断与用药是否相符\n";
            qrot->exec("select center_name, his_name from fin_com_compare where fixmedins_hilist_id = '" + item + "'");
            if(!qrot->next())
            {
                QMessageBox::information(this, "注意", item_name + " 在 fin_com_compare 中没有记录！");
                return false;
            }

            QString item_his, item_center;
            item_his = qrot->value(1).toString();
            item_center = qrot->value(0).toString();

            QStringList diag_list;
            if(!qrmt->value("diag1c").toString().isEmpty())
                diag_list<<qrmt->value("diag1c").toString();
            if(!qrmt->value("diag2c").toString().isEmpty())
                diag_list<<qrmt->value("diag2c").toString();
            if(!qrmt->value("diag3c").toString().isEmpty())
                diag_list<<qrmt->value("diag3c").toString();

            for( int i = 0; i < diag_list.size(); i++)
            {
                sq = "select * from reci_ck_diag_drug where item_name in('"+item_center+"','"+item_his+"') and ";
                sq += " diag_code_nat = ('" + diag_list[i] + "')";
                qrm->exec(sq);
                qDebug()<<"check if " + diag_list[i] + " and " << item_his << " is invalid : " << sq;

                if( !qrm->next())
                {
                    //未找到记录，诊断与用药不符
                    QMessageBox::information(this, "注意", item_his + " 与诊断不相符！");
                    QString diags = qrmt->value("diag1").toString();
                    if(!qrmt->value("diag2").toString().isEmpty())
                    {
                        diags.append(", " + qrmt->value("diag2").toString());
                    }
                    if(!qrmt->value("diag3").toString().isEmpty())
                    {
                        diags.append(", " + qrmt->value("diag3").toString());
                    }

                    QString err_msg = item_his + " 与诊断 " +  diags + " 不匹配";

                    save_recipe_error("诊断与用药不匹配", err_msg);

                    qDebug()<<"诊断与用药不相符，"<<err_msg<<"\n";

                    return false;
                }

            }

            QString dose_unit_limit = qrm->value("amount_unit").toString();
            double day_amount_limit = qrm->value("amount_limit").toDouble();

            //找到合理诊断，检查日用量是否合理
            qDebug()<<"检查日用量是否合理\n";
            QString dose_unit = qrmt->value("dose_unit").toString();
            double day_amount = qrmt->value("once_dose").toDouble() * qrmt->value("freq_days").toDouble();
            qDebug()<<"dose_unit , day_amount : "<<dose_unit
                   <<" , "<<QString::number(day_amount)<<"\n";

            QString str_dose_use = QString::number(day_amount)
                    + dose_unit;

            if(dose_unit == "g" || dose_unit == "克")
            {
                //以 mg 为比较单位
                day_amount = day_amount * 1000;
                qDebug()<<"change dose_unit from g to mg \n";
            }

            QString str_dose_limit = QString::number(day_amount_limit)
                    + dose_unit_limit;

            qDebug()<<"dose_unit_limit , day_amount_limit : "
                   <<dose_unit_limit<<" , "
                  <<QString::number(day_amount_limit)<<"\n";

            if(dose_unit_limit == "g" || dose_unit_limit == "克")
            {
                //以 mg 为比较单位
                day_amount_limit = day_amount_limit * 1000;
                qDebug()<<"change day_amount_limit from g to mg \n";
            }

            if(!dose_unit_limit.isEmpty()   //非空，为有效设置
                    &&!qFuzzyCompare(day_amount, day_amount_limit)  //不相等
                    && day_amount > day_amount_limit )  //处方日用量大于极限用量
            {
                QMessageBox::information(this, "注意", item_his
                                         + " 日用量极限为 "
                                         + str_dose_limit +"！");

                QString err_msg = item_his + " 日用量 " +  str_dose_use ;

                save_recipe_error("超最大日用量", err_msg);
                qDebug()<<"超最大日用量"<<err_msg<<"\n";

                return false;

            }

            //职级限定
            sq = "select duty_constrain from pha_com_baseinfo where drug_code = '"
                    + qrmt->value("item_code").toString() + "'";
            qDebug()<<"检索药品职级限定："<<sq<<"\n";
            qrot->exec(sq);
            qrot->next();
            int drug_grade;

            if(qrot->value(0).toString().isEmpty())
            {
                drug_grade = 4;        //最大可能值 4
            }else{
                drug_grade = qrot->value(0).toInt();
            }

            int usr_grade = pub::dr_profttl.toInt();

            qDebug()<<"drug_grade and usr_grade : "<<QString::number(drug_grade)<<","<<QString::number(usr_grade);
            if(usr_grade > drug_grade)
            {
                msg = item_name + "，超出处方医师职级允许范围，请在上级医师指导下使用！";
                QMessageBox::information(this, "注意", msg);

                QString err_msg = item_name + " 要求职级： "
                        + QString::number(drug_grade)
                        + ", 医师职级："
                        + QString::number(usr_grade);

                save_recipe_error("超职级用药", err_msg);
                qDebug()<<"超职级限定"<<err_msg<<"\n";

                sq = "insert into PHA_STO_RECIPE_SENIOR_CHECK"
                     " (recipe_no ,clinic_code, card_no, dept_code, patient_name, "
                     " apply_doct_code, apply_doct_name, apply_date,"
                     " item_code, item_name, grade_need, check_status) "
                     "values ('%1', '%2', '%3', '%4','%5',"
                     "'%6', '%7', sysdate ,"
                     "'%8', '%9', '%10', '0')";
                sq = sq.arg("0").arg(mpPatientInfo["clinic_code"]).arg(mpPatientInfo["card_no"])
                        .arg(pub::dp_code).arg(mpPatientInfo["name"])
                        .arg(pub::usr_code).arg(pub::usr_name)
                        .arg(qrmt->value("item_code").toString()).arg(item_name).arg(drug_grade);

                qDebug()<<"写入超职级限定申请表："<<sq<<"\n";
                qrot->exec(sq);


            }

            //选用剂型与给药途径是否适宜
            sq = "select doseform_code, doseform_name from reci_ck_doseform_usage where doseform_code = '";
            sq += qrmt->value("DOSE_MODEL_CODE").toString() + "'";
            sq += " and  usage_name = '" + qrmt->value("usages").toString() + "'";

            qDebug()<<"选用剂型与给药途径是否适宜:"<<sq<<"\n";

            qrm->exec(sq);
            if(!qrm->next())
            {
                QMessageBox::StandardButton bt;
                bt = QMessageBox::question(this, "注意", item_his + " 用药途径不符合常规约定，是否超常规使用？");

                QString err_msg;

                if(bt == QMessageBox::Yes)
                {
                    err_msg = item_his + " ，" +  qrmt->value("usages").toString();
                    save_recipe_error("超常规途径用药", err_msg);
                }
                else
                {
                    err_msg = item_his + " ，" +  qrmt->value("usages").toString();
                    save_recipe_error("用药途径与剂型冲突", err_msg);

                    return false;
                }

                qDebug()<<"用药途径 :"<<err_msg<<"\n";

            }

            //是否年龄限制
            sq = "select condition_code from reci_ck_drug_constrain where "
                 "  drug_name in('" + item_his + "','" + item_center + "') and constrain_type = '年龄' ";
            qDebug()<<"是否符合年龄限制:"<<sq<<"\n";
            qrm->exec(sq);
            while(qrm->next())
            {
                //年龄可能是封闭年龄段
                QString cond, val;
                cond = pub::getStr(qrm->value(0).toString(), " ", 1);
                val = pub::getStr(qrm->value(0).toString(), " ", 2);

                bool passed = true;

                double age_p,age_c; //患者年龄，限制年龄
                age_p = mpPatientInfo["age"].toDouble();
                age_c = val.toDouble();

                if(cond == ">=")
                {
                    if(!qFuzzyCompare(age_c, age_p) && age_p < age_c )
                    {
                        passed = false;
                    }
                }
                else if(cond == "<=")
                {
                    if(!qFuzzyCompare(age_c, age_p) && age_p > age_c )
                    {
                        passed = false;
                    }
                }
                else
                {

                }

                if(!passed)
                {
                    QMessageBox::information(this, "注意", item_his + " 超年龄范围用药！");

                    QString err_msg = item_his + " ，要求 " + cond + val + "， 实际患者 " + mpPatientInfo["age"];
                    save_recipe_error("超年龄范围用药", err_msg);
                    qDebug()<<"超年龄范围用药"<< err_msg<<"\n";
                    return false;
                }
            }

            //是否符合性别限制
            sq = "select condition_code from reci_ck_drug_constrain where "
                 "  drug_name in('" + item_his + "','" + item_center + "') and constrain_type = '性别' ";
            qDebug()<<"是否符合性别限制:"<<sq<<"\n";
            qrm->exec(sq);
            if(qrm->next())
            {
                QString cond = qrm->value(0).toString();

                if( cond != mpPatientInfo["gender"])
                {
                    QMessageBox::information(this, "注意", item_his + " 超性别限定用药！");

                    QString err_msg = item_his + " ，要求 " + cond + "， 实际患者 " + mpPatientInfo["gender"];
                    save_recipe_error("超性别限定用药", err_msg);
                    qDebug()<<"超性别限定用药"<< err_msg<<"\n";
                    return false;
                }
            }

            drug_names += ",'" + item_his + "','" + item_center + "'";

            /*
用药不适宜处方

1.处方用药与诊断是否相符；
4.选用剂型与给药途径是否适宜；
6.是否存在配伍禁忌；
4.无正当理由为同一患者同时开具2种以上药理作用相同药物。
5.是否有重复给药和相互作用情况，包括西药、中成药、中成药与西药、
中成药与中药饮片之间是否存在重复给药和有临床意义的相互作用；

3.处方剂量、用法是否正确，单次处方总量是否符合规定；

7.是否有用药禁忌：儿童、老年人、孕妇及哺乳期妇女、脏器功能不全患者用药是否有禁忌使用的药物，
患者用药是否有食物及药物过敏史禁忌证、诊断禁忌证、疾病史禁忌证与性别禁忌证；
            //限年龄
            //限性别

诊断与年龄、性别冲突

3.无正当理由超说明书用药。


2.规定必须做皮试的药品，是否注明过敏试验及结果的判定；
过敏史？
8.溶媒的选择、用法用量是否适宜，静脉输注的药品给药速度是否适宜；
9.是否存在其他用药不适宜情况。
2.遴选的药品不适宜。
4.无正当理由不首选国家基本药物的。




*/
        }
        //QMessageBox::information(this, "注意", "item is " +item);
        if(type == "4")
        {
            //草药，颗粒
        }
    }

    sq = "select count(conflict_type),conf_name,conflict_type from reci_ck_drug_conflict "
         " where drug_name in(" + drug_names + ") group by conf_name,conflict_type";
    qrm->exec(sq);
    while(qrm->next())
    {
        if(qrm->value(0).toInt() > 1)
        {
            QMessageBox::information(this, "注意", "触发药品配伍冲突限制 "
                                     + qrm->value(1).toString() +", " + qrm->value(2).toString());

            QString err_msg = qrm->value(1).toString() +", " + qrm->value(2).toString();
            save_recipe_error("药品配伍冲突", err_msg);

            return false;

        }
    }

    //诊断是否存在性别冲突
    QString diags = "'" + ui->cbbDiag1->currentText() + "','";
    diags += ui->cbbDiag2->currentText() + "','";
    diags += ui->cbbDiag3->currentText() + "'";

    sq = "select gend , diag_name from reci_ck_diag_gend "
         " where diag_name in (" + diags + ") ";
    qrm->exec(sq);
    while(qrm->next())
    {
        QString gd = qrm->value(0).toString();
        if( gd != "不限" && gd != mpPatientInfo["gender"] )
        {
            QMessageBox::information(this, "注意", "诊断与性别不符 ！ ");

            QString err_msg = qrm->value(1).toString() +" 限制性别为 " + qrm->value(0).toString();
            save_recipe_error("诊断与性别不符", err_msg);
            return false;
        }
    }

    qDebug()<<"药品项目检查结束。\n";

    return true;
}

bool Form_ys_bzgl::statusCheck(QString mode)
{
    //mode : base 基础检查， case 病志， item 处方每个项目， recipe 最终保存处方

    QString tmp;

    if(ui->le_diag1->text().isEmpty())
    {
        ui->ckbDiag1->setChecked(false);
    }
    else
    {
        tmp = getNatCode(ui->cbbDiag1->currentText().trimmed(), "2");
        if(tmp.isEmpty())
        {
            QMessageBox::information(this, "注意", "诊断 "
                                     + ui->cbbDiag1->currentText().trimmed()
                                     + " 无效，请重新维护 icpc 信息！");
            return false;
        }
    }

    if(ui->le_diag2->text().isEmpty())
    {
        ui->ckbDiag2->setChecked(false);
    }
    else
    {
        tmp = getNatCode(ui->cbbDiag2->currentText().trimmed(), "2");
        if(tmp.isEmpty())
        {
            QMessageBox::information(this, "注意", "诊断 "
                                     + ui->cbbDiag2->currentText().trimmed()
                                     + " 无效，请重新维护 icpc 信息！");
            return false;
        }
    }

    if(ui->le_diag3->text().isEmpty())
    {
        ui->ckbDiag3->setChecked(false);
    }
    else
    {
        tmp = getNatCode(ui->cbbDiag3->currentText().trimmed(), "2");
        if(tmp.isEmpty())
        {
            QMessageBox::information(this, "注意", "诊断 "
                                     + ui->cbbDiag3->currentText().trimmed()
                                     + " 无效，请重新维护 icpc 信息！");
            return false;
        }
    }

    if( !ui->ckbDiag1->isChecked()
            && !ui->ckbDiag2->isChecked()
            && !ui->ckbDiag3->isChecked() )
    {
        QMessageBox::information(this, "注意", "至少需要关联一项诊断之后才可以录入项目！");
        return false;
    }



    if(mpPatientInfo["clinic_code"].isEmpty())
    {
        QMessageBox::information(this, "注意", "患者信息无效！");
        return false;
    }

    //检查是否存在接诊冲突
    sq = " select see_docd from fin_opr_register "
         " where valid_flag = '1' "
         " and clinic_code ='" + mpPatientInfo["clinic_code"] + "' ";

    qDebug()<<"提取本次挂号接诊医师信息 ： "<<sq;

    qrot->exec(sq);
    if(qrot->next())
    {
        //保存最新接诊医师信息
        mpPatientInfo["see_docd"] = qrot->value(0).toString();
    }

    if( !mpPatientInfo["see_docd"].isEmpty() && mpPatientInfo["see_docd"] != pub::usr_code)
    {
        if(!ui->ckb_no_own->isChecked())
        {
            QMessageBox::information(this, "注意", "非本人接诊记录，不能修改！");
            return false;
        }
    }

    if(ui->lePhone->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "联系电话不可以为空！");
        return false;
    }

    if(mode == "case")//病志
    {
        if(ui->cbbReason->currentIndex() < 0)
        {
            if(ui->tab_recipe_new->isHidden())
                QMessageBox::information(this, "注意", "就诊原因不可以为空！");
            return false;
        }
        if(ui->leHzzs->text().trimmed().isEmpty())
        {
            if(ui->tab_recipe_new->isHidden())
                QMessageBox::information(this, "注意", "患者主诉不可以为空！");
            return false;
        }
        if(ui->pt_current_symp->toPlainText().trimmed().isEmpty())
        {
            if(ui->tab_recipe_new->isHidden())
                QMessageBox::information(this, "注意", "现病史不可以为空！");
            return false;
        }
        if(ui->leJws->text().trimmed().isEmpty())
        {
            if(ui->tab_recipe_new->isHidden())
                QMessageBox::information(this, "注意", "既往史不可以为空！");
            return false;
        }
        if(ui->leGms->text().trimmed().isEmpty())
        {
            if(ui->tab_recipe_new->isHidden())
                QMessageBox::information(this, "注意", "过敏史不可以为空！");
            return false;
        }
        if(ui->pt_body_check->toPlainText().trimmed().isEmpty()
                && !ui->ckb_no_patient->isChecked())
        {
            //未见患者可以不录入体格检查
            if(ui->tab_recipe_new->isHidden())
                QMessageBox::information(this, "注意", "体格检查不可以为空！");
            return false;
        }

        //中医或中西医
        if(ui->cbbDiag1->currentText().isEmpty()
                && ui->cbbDiag2->currentText().isEmpty()
                && ui->cbbDiag3->currentText().isEmpty()
                )
        {
            QMessageBox::information(this, "注意", "西医诊断不可以为空！");
            return false;
        }

        QString mod = ui->cbbBzmb->currentText().trimmed();

        if(ui->rb_mode_tr->isChecked() || ui->rb_mode_tr_med->isChecked())
        {
            if( !ui->ckb_no_patient->isChecked())
            {
                //中医模式 ，非 “未见患者”，进行校验

                if( (!ui->cbbDiag1->currentText().isEmpty()
                     && !ui->cbb_tr_diag1->currentText().isEmpty()
                     && !ui->cbb_tr_symptom1->currentText().isEmpty()
                     )
                        ||
                        (ui->cbbDiag1->currentText().isEmpty()
                         && ui->cbb_tr_diag1->currentText().isEmpty()
                         && ui->cbb_tr_symptom1->currentText().isEmpty()
                         )
                        )
                {
                }
                else
                {
                    QMessageBox::information(this, "注意", "中医诊断 1 不完整！");
                    return false;

                }

                if(ui->pt_tr_diag->toPlainText().isEmpty())
                {
                    QMessageBox::information(this, "注意", "中医辨证不可以为空！");
                    return false;
                }

                if(ui->pt_similar_syndrom->toPlainText().trimmed().isEmpty())
                {
                    QMessageBox::information(this, "注意", "中医类证鉴别不可以为空！");
                    return false;
                }

                if(ui->pt_treat_tr->toPlainText().trimmed().isEmpty())
                {
                    QMessageBox::information(this, "注意", "中医治则不可以为空！");
                    return false;
                }

                if(ui->pt_body_check_tr->toPlainText().trimmed().isEmpty())
                {
                    //if(ui->tab_recipe_new->isHidden())
                    QMessageBox::information(this, "注意", "中医查体不可以为空！");
                    return false;
                }

                if((ui->cbb_tr_diag1->currentText().isEmpty() ^ ui->cbb_tr_symptom1->currentText().isEmpty())
                //        || (ui->cbb_tr_diag2->currentText().isEmpty() ^ ui->cbb_tr_symptom2->currentText().isEmpty())
                //        || (ui->cbb_tr_diag3->currentText().isEmpty() ^ ui->cbb_tr_symptom3->currentText().isEmpty())
                        )
                {
                    //二、三诊断不做完整性校验
                    QMessageBox::information(this, "注意", "中医诊断与证候不匹配！");
                    return false;
                }

            }

        }

        if(ui->cbb_conclusion->currentText().isEmpty())
        {
            QMessageBox::information(this, "注意", "诊疗结论无效！");
            return false;
        }

        if(!ui->le_next_call->text().trimmed().isEmpty())
        {
            int test = ui->le_next_call->text().toUInt();
            if(test < 1)
            {
                QMessageBox::information(this, "注意", "随访日期数值无效！");
                return false;
            }
        }
    }

    if(mode == "item")
    {
        if(ui->cbbPackUnit->currentText().isEmpty())
        {
            QMessageBox::information(this, "注意", "数量单位不可以为空！");
            return false;
        }

        if(ui->spCnt->value() < 1  )
        {
            QMessageBox::information(this, "注意", "数量不正确！");
            return false;
        }

        if(ui->cbbPackUnit->currentIndex() == -1 )
        {
            QMessageBox::information(this, "注意", "项目单位不允许空！");
            return false;

        }

        if(ui->leItemName->text().isEmpty())
        {
            QMessageBox::information(this, "注意", "项目名称不允许空！");
            return false;
        }

        if(ui->cbbRange->currentText() == "西药中成药") //
        {
            double onceDose = ui->leUseCnt->text().toDouble();
            if( qFuzzyCompare( onceDose ,0) || onceDose < 0)
            {
                QMessageBox::information(this, "注意", "药品单次用量无效！");
                return false;
            }
            if(ui->cbbUsage->currentIndex() == -1
                    || ui->cbbFreq->currentIndex() == -1
                    //|| ui->cbbDoseUnit->currentIndex() == -1
                    )

            {
                QMessageBox::information(this, "注意", "药品项目所有信息都必须完整！");
                return false;
            }

        }

        if(ui->cbbRange->currentText() == "诊疗") //
        {
            if(ui->cbbFreq->currentIndex() == -1 )
            {
                QMessageBox::information(this, "注意", "诊疗项目频次不可以为空！");
                return false;
            }

        }

    }

    if(mode == "recipe")
    {
        int count_all, count_herb;  //全部项目数量，草药项目数量
        qrm->exec("select count(item_type) from tmp_recipe ");
        qrm->next();
        count_all = qrm->value(0).toUInt();

        if(count_all < 1)
        {
            QMessageBox::information(this, "注意", "未录入处方内容！");
            return false;
        }

        //中草药检查
        qrm->exec("select count(item_type) from tmp_recipe where item_type = '4'");
        qrm->next();
        count_herb = qrm->value(0).toUInt();

        if(count_herb > 0 && count_herb != count_all)
        {
            QMessageBox::information(this, "注意", "草药处方必须单独开具！");
            return false;
        }

        if(count_herb > 0) // "中草药"
        {

            //检查处方限量
            int herb_days = ui->le_tr_days->text().toUInt();
            if( herb_days < 1)
            {
                QMessageBox::information(this, "注意", "草药剂数数量无效！");
                return false;
            }

            double onceDose = ui->leUseCnt->text().toDouble();
            if( qFuzzyCompare( onceDose ,0) || onceDose < 0)
            {
                QMessageBox::information(this, "注意", "药品单次用量无效！");
                return false;
            }

            if(ui->cbbUsage->currentIndex() == -1
                    || ui->cbbFreq->currentIndex() == -1
                    )
            {
                QMessageBox::information(this, "注意", "药品用法和使用频次信息必须完整！");
                return false;
            }

            QString pact_mode;
            if(ui->rb_reci_ct_insu->isChecked())
            {
                pact_mode = "医保";       //医保
            }
            else
            {
                pact_mode = "现金";       //现金
            }

            sq = "select days_count_single, days_count_current from reci_ck_days "
                 " where fee_type = '中草药' and pact_type ='" + pact_mode + "'";

            qrmt->exec(sq);
            if(!qrmt->next())
            {
                QMessageBox::warning(this, "注意", "找不到处方限量标准！");
                return false;
            }

            int days_count_single = qrmt->value(0).toInt(); //单张处方日期限量
            int days_count_current = qrmt->value(1).toInt();//最多允许患者保留几张处方

            if(herb_days > days_count_single)
            {
                QMessageBox::information(this, "注意", "处方天数超限量！");
                save_recipe_error("单张处方超限量", "草药使用天数为 " + QString::number(herb_days) + " 天");
                return false;
            }


            //计算历史开药数据
            sq = "select distinct days, oper_date from fin_opb_feedetail where card_no = '";
            sq += mpPatientInfo["card_no"] + "' and fee_code = '003'";
            sq += " and oper_date > sysdate - (" + QString::number(days_count_single)
                    + " * " + QString::number(days_count_current) + ")";
            sq += " and cancel_flag = '1' "; //and pay_flag = '1'
            sq += " order by oper_date desc ";
            qro->exec(sq);
            qDebug()<<"检索 N 个处方周期累计用量："<<sq;

            int count = 0;
            int maxCount = 0;  //最大可用处方天数
            int realDays = 0;   //处方日期至当前日期的天数
            QDate curD, RecipeD,maxD;

            curD = QDate::currentDate();
            while(qro->next())
            {
                RecipeD = qro->value(1).toDate();
                count += qro->value(0).toInt();
                realDays = RecipeD.daysTo(curD);

                if(count - realDays > maxCount)
                {
                    //保存最大可用处方天数的处方日期
                    maxCount = count - realDays;
                    maxD = RecipeD;
                }
            }

            //周期累计 ，是否超限量

            // 之前余量 + 本日 = 当前患者手中最大可用数量 ，是否超？
            QString msg;
            if(maxCount + herb_days > days_count_single * days_count_current)
            {
                msg = "本次开药后患者应有 " + QString::number(maxCount + herb_days) + " 天用量，超出最大合理范围！";
                QMessageBox::information(this, "注意", msg);
                QString err_msg = "本次开药后 草药 用量达到 " + QString::number(maxCount + herb_days) + " 天";
                save_recipe_error("累计超量",err_msg);

                return false;
            }

            //完善草药处方信息
            sq = "update tmp_recipe set "
                 "recipe_days = %1, "  //处方天数
                 "usages = '%2', "  //用法
                 "usage_code = '%3',"  //用法代码
                 "once_dose = %4, "  //单次用量
                 "dose_unit = '%5',"  //用量单位
                 "frequency = '%6',"  //频次
                 "frequency_code = '%7'";   //频次代码
                 //"qty = qty * %1 "   //药品数量
                 //"amount = price * qty ";   //金额

            sq = sq.arg(QString::number(herb_days));
            sq = sq.arg(ui->cbbUsage->currentText());
            sq = sq.arg(pub::getDicC("给药途径",ui->cbbUsage->currentText()));
            sq = sq.arg(QString::number(onceDose));
            sq = sq.arg(ui->le_dose_unit->text());
            sq = sq.arg(ui->cbbFreq->currentText());
            sq = sq.arg(pub::getDicN("频次", qro->value("frequency_code").toString()));

            qDebug()<<"补齐草药处方基础信息："<<sq;
            if(!qrm->exec(sq))
            {
                QMessageBox::information(this, "注意", "补齐草药处方基础信息 sql 失败！");
                return false;
            }

        }

        //医保患者进行代取药信息检查
        sq = " select upld_flg2 from fin_opr_register "
             " where  clinic_code = '"
                + mpPatientInfo["clinic_code"] + "' order by trans_type";
        qDebug()<<"检查是否保存过2261信息："<<sq;

        if(!qrot->exec(sq))
        {
            QMessageBox::warning(this,"错误","提取 fin_ipr_register 信息失败！");
            return false;
        }

        qrot->next();

        if(qrot->value(0).toString() == "0")
        {
            //未上传过2261
            if(!busi_2261())
            {
                return false;
            }
        }

        QMap<QString,QString> diagInRecipe;   //处方中出现过的诊断
        sq = "select diag1, diag2, diag3 from tmp_recipe  ";//where item_type = '1'
        qrmt->exec(sq);

        while(qrmt->next())
        {
            if(!qrmt->value(0).toString().isEmpty())
            {
                diagInRecipe[qrmt->value(0).toString()] = qrmt->value(0).toString();
            }
            if(!qrmt->value(1).toString().isEmpty())
            {
                diagInRecipe[qrmt->value(1).toString()] = qrmt->value(1).toString();
            }
            if(!qrmt->value(2).toString().isEmpty())
            {
                diagInRecipe[qrmt->value(2).toString()] = qrmt->value(2).toString();
            }
        }

        QMap<QString,QString> diagInScreen;    //屏幕显示的诊断

        if(!ui->cbbDiag1->currentText().isEmpty())
        {
            diagInScreen[ui->cbbDiag1->currentText()] = ui->cbbDiag1->currentText();
        }
        if(!ui->cbbDiag2->currentText().isEmpty())
        {
            diagInScreen[ui->cbbDiag2->currentText()] = ui->cbbDiag2->currentText();
        }
        if(!ui->cbbDiag3->currentText().isEmpty())
        {
            diagInScreen[ui->cbbDiag3->currentText()] = ui->cbbDiag3->currentText();
        }

        //交叉核验处方诊断与屏显诊断是否相符
        QString diagErrInRecipe, diagErrInScreen;
        foreach(QString d, diagInRecipe)
        {
            if(diagInScreen[d].isEmpty())
            {
                diagErrInRecipe += d + ", ";
            }
        }

        foreach(QString d, diagInScreen)
        {
            if(diagInRecipe[d].isEmpty())
            {
                diagErrInScreen += d + ", ";
            }
        }

        if(!diagErrInRecipe.isEmpty())
        {
            QMessageBox::information(this, "注意", "处方项目中的诊断 " + diagErrInRecipe + " 与即将保存的诊断不一致！");
            return false;
        }
        if(!diagErrInScreen.isEmpty())
        {
            QMessageBox::information(this, "注意", "即将保存的诊断 " + diagErrInScreen + " 未出现在处方项目中！");
            //return false;
        }
    }
    return true;
}

void Form_ys_bzgl::save_recipe_error(QString type, QString describe)
{
    sq = "insert into ys_bz_e_recipe_check (oper_date, clinic_code,"
         " conflict_type, conflict_describe, "
         " doct_code, doct_name )"
         " values ( now(), ";
    sq += "'" + mpPatientInfo["clinic_code"] + "',";
    sq += "'" + type + "',";
    sq += "'" + describe + "',";
    sq += "'" + pub::usr_code + "',";
    sq += "'" + pub::usr_name + "')";
    if(!qrm->exec(sq))
    {
        qDebug()<<"save ys_bz_e_recipe_check error : "<<sq;
    }

}

bool Form_ys_bzgl::call_2261()
{

    //上传2261信息
    sq = "select psn_no, setl_id, mdtrt_id from fin_ipr_siinmaininfo "
         " where inpatient_no = '" + mpPatientInfo["clinic_code"] + "' order by balance_no";
    qDebug()<<"提取2261需要的节点信息："<<sq;
    if(!qro->exec(sq)){
        QMessageBox::warning(this,"错误","提取 fin_ipr_siinmaininfo 信息失败！");
        return false;
    }
    if(!qro->next())
    {
        QMessageBox::warning(this,"错误","fin_ipr_siinmaininfo 中找不到有效医保交易信息！");
        return false;
    }

    QJsonObject in;   //医保交易入参信息
    QJsonObject inpud; //data 节点
    QJsonArray inpua;

    inpud.insert("setl_id", qro->value("setl_id").toString());	//结算ID	字符型	30	　	Y
    inpud.insert("mdtrt_id", qro->value("mdtrt_id").toString());	//	就诊ID	字符型	30	　	Y
    inpud.insert("psn_no", qro->value("psn_no").toString());	//	人员编号	字符型	30	　	Y
    inpud.insert("trustee_name", ui->leTrustee->text());	// 	受托人姓名	字符型	50		Y
    inpud.insert("trustee_certno", ui->leTrusteeI->text());	//	受托人身份证号码	字符型	50		Y
    inpud.insert("trustee_tel", ui->leTrusteeP->text());	//	受托人联系电话	字符型	50		Y
    inpud.insert("principal_name", mpPatientInfo["name"]);	//	委托人姓名	字符型	50		Y
    inpud.insert("principal_certno", mpPatientInfo["idenno"]);	//	委托人身份证号码	字符型	50		Y
    inpud.insert("principal_tel", mpPatientInfo["rela_phone"]);	//	委托人联系电话	字符型	50		Y
    inpud.insert("rlts", ui->cbbTrusteeRlt->currentText());	//	受托人与委托人的关系	字符型	50		Y
    inpud.insert("vali_flag","1");	//	有效标志	字符型	3		Y
    inpua<<inpud;
    in.insert("data", inpua); //

    QString info;   //返回信息
    QJsonObject jsonRet; //返回 json 数据

    dlgDelay->setText("上传代取药信息。。。");
    dlgDelay->setModal(true);
    dlgDelay->setNeedClose(false);
    dlgDelay->show();
    qApp->processEvents();

    if( ! pub::call_business("2261", in, info, jsonRet, "", true ,
                             manager, request, mpPatientInfo["clinic_code"]))
    {
        QMessageBox::warning(this, "注意", info);
        qDebug()<<"2261 business return error.";
        qDebug()<<info;

        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();

        return false;
    }
    else
    {

        QJsonObject j = jsonRet.value("result").toObject();
        if(j.value("retRslt").toInt() != 0)
        {
            QMessageBox::warning(this, "注意", " 上传代取药信息失败：" + j.value("msgRslt").toString()) ;

            dlgDelay->setNeedClose(true);
            dlgDelay->closeWindow();

            return false ;
        }
        else
        {
            sq = "update fin_opr_register set upld_flg2 = '1' where clinic_code = '"
                    + mpPatientInfo["clinic_code"] + "'";
            qro->exec(sq);
        }
    }

    dlgDelay->setNeedClose(true);
    dlgDelay->closeWindow();

    return true;
}

void Form_ys_bzgl::on_pbSave_clicked()
{
    if(!ui->leItemName->text().isEmpty()){
        QMessageBox::information(this, "注意", "有录入未完成的处方内容，清除或保存后再继续！");
        return;
    }

    if(!statusCheck("recipe")) return;

    if(!undrug_check()) return;

    if(!drugCheck()) return;

    //bool bzFinished = true;   //病志是否完整
    if(!saveBZ(1))
    {
        return;
    }

    qApp->processEvents();

    //提取挂号信息,插入 met_ord_recipedetail, fin_opb_feedetail 需要使用
    sq = "select dept_code from FIN_OPR_REGISTER where trans_type = '1' and clinic_code = '"
            + mpPatientInfo["clinic_code"] + "' ";
    qrot->exec(sq);
    qrot->next();
    mpPatientInfo.insert("dept_code", qrot->value(0).toString());

    qro->exec("select seq_seeno.nextval from dual");
    qro->next();
    QString see_no = qro->value(0).toString(); //看诊序号

    qro->exec("select seq_fin_opb_recipeseq.nextval from dual");
    qro->next();
    QString recipe_seq = qro->value(0).toString(); //收费序号
    sq = "select item_code, item_name ,frequency , usages, usage_code, once_dose, dose_unit ,qty, qty_unit, "
         "item_type ,exe_deptcode,pack_qty, amount, "
         " diag1 ,diag2,diag3 , diag1c ,diag2c ,diag3c, price, specs, drug_quality,"
         " DOSE_MODEL_CODE,SELF_MADE,FEE_CODE,CLASS_CODE,BASE_DOSE, "
         "(select dept_name from com_department d where d.dept_code = exe_deptcode limit 1) ext_name, "
         " recipe_days,center_grade, package_name, package_code,center_code"
         " from tmp_recipe order by exe_deptcode,item_type,drug_quality,seq";
    qrm->exec(sq);

    //2024-11-22,comb_no, 可以用来关联 met_ord_recipedetail 和 fin_opb_feedetail 两个表
    QString comb_no; //组合号。感觉无甚鸟用。暂按项目流水号方式生成和保存。

    QString recipe_item_id; //处方项目流水号
    QString recipe_no;     //处方号
    recipe_list_5465.clear();
    //分配新处方号条件：
    //1、执行科室发生变化
    //2、药品属性发生变化
    //3、西药、中成药，处方内项目流水大于5
    //4、治疗处方内项目流水大于8
    //5、草药，处方内项目流水大于32
    int sequence_no = 0;    //处方内项目流水号
    int sort_id = 0;    //全部项目流水号
    QString exec_dpcd = "";      //跟踪执行科室代码变化
    QString drug_quality = "";  //跟踪药品属性变化
    QString item_type = "";  //跟踪项目属性变化

    QStringList sqls;   //准备向线程传送的sql集合

    bool first = true; //首次循环标志
    while(qrm->next())
    {

        QString fee_code = qrm->value("fee_code").toString();   //收费类别

        //如果是西药中成药, 进行库存数量校验
        if(qrm->value("item_type").toString() == "1")
        {

            sq = "select store_sum from pha_com_stockinfo ";
            sq += " where store_sum > 0 and drug_dept_code = '" + qrm->value("exe_deptcode").toString() + "' ";
            sq += " and drug_code = '" + qrm->value("item_code").toString() + "'";
            qDebug()<<"check store_sum : "<<sq;
            qro->exec(sq);
            if(!qro->next()){
                QMessageBox::information(this, "注意", "药品项目"
                                         + qrm->value("item_name").toString()
                                         + "在" + qrm->value("ext_name").toString() + "无有效库存！");
                return;
            }
            if(qro->value(0).toInt() < qrm->value("qty").toInt() * qrm->value("pack_qty").toInt())
            {
                QMessageBox::information(this, "注意", "药品项目"
                                         + qrm->value("item_name").toString()
                                         + "在" + qrm->value("ext_name").toString() + "库存不足！");
                return;
            }
        }

        if( fee_code == "004" || fee_code == "007")
        {
            //辅诊项目
            sq = "replace into ys_bz_e_lib (jlrq, xmmc, id, clinic_code, fee_code)"
                 " values(curdate(), '%1', '%2', '%3', '%4')";

            sq = sq.arg(qrm->value("package_name").toString())
                    .arg(qrm->value("package_code").toString())
                    .arg(mpPatientInfo["clinic_code"] )
                    .arg(fee_code);

            qDebug()<<"保存辅诊项目 : "<<sq;

            if(!qrmt->exec(sq))
            {
                QMessageBox::information(this, "注意", "保存辅诊项目失败！");
                return;
            }
        }

        sort_id ++;

        qDebug()<<"exec_dpcd:"<<exec_dpcd<<","<<qrm->value("exe_deptcode").toString();
        qDebug()<<"item_type:"<<item_type<<","<<qrm->value("item_type").toString();
        qDebug()<<"drug_quality:"<<drug_quality<<","<<qrm->value("drug_quality").toString();
        qDebug()<<"sequence_no:"<<QString::number(sequence_no);
        qDebug()<<"first :"<<first;


        if(exec_dpcd != qrm->value("exe_deptcode").toString()  //执行科室发生变化
                || item_type != qrm->value("item_type").toString()  //项目属性发生变化
                || drug_quality != qrm->value("drug_quality").toString()  //药品属性发生变化
                || (sequence_no > 5 && (fee_code == "001" || fee_code == "002")) //西药中成药处方项目数大于5
                || (sequence_no > 32 && fee_code == "003" ) //草药数大于32
                || (sequence_no > 8 && fee_code == "005" ) //治疗项目数大于8
                || first    //首次进入循环，必须分配处方号
                )
        {
            qro->exec("select SEQ_OPB_RECIPE_NO.nextval from dual");
            qro->next();
            recipe_no = qro->value(0).toString(); //收费序号
            sequence_no = 1;
            first = false;
            recipe_list_5465 << recipe_no;
        }

        qro->exec("select SEQ_MET_ORDER_ID.nextval from dual");
        qro->next();
        recipe_item_id = qro->value(0).toString(); //处方项目流水号
        qro->exec("select seq_met_order_combono.nextval from dual");
        qro->next();
        comb_no = qro->value(0).toString(); //组合号


        //为sql阅读性，先插入必须字段，再更新其它字段。
        //数据表字段命名混乱，使用时需要注意！！需要注意！！需要注意！！
        //fin_opb_feedetail.mo_order = met_ord_recipedetail.sequence_no
        //fin_opb_feedetail.comb_no = met_ord_recipedetail.comb_no
        //fin_opb_feedetail.recipe_seq = met_ord_recipedetail.recipe_feeseq
        //fin_opb_feedetail.sequence_no = met_ord_recipedetail.recipe_seq

        //fin_opb_feedetail.recipe_seq != met_ord_recipedetail.recipe_seq

        //fin_opb_feedetail 非空字段：处方号 recipe_no，处方内项目流水号 sequence_no ，交易类型 trans_type，
        // 项目编码 item_code，项目名称 item_name, 发票序号 invoice_seq，医嘱流水号 mo_order
        //调用sequence生成的数据也一并插入：组合号 comb_no,收费序列号 recipe_seq

         if(mpPatientInfo["pact_code"] == "2" && ui->rb_reci_ct_cash->isChecked())
         {
             //医保患者，现金开药
             sq = "oinsert into fin_opb_insu_cash "
                  " (recipe_no,"
                  "clinic_code,"
                  "card_no,"
                  "doct_code,"
                  "doct_dept,"
                  "item_code,"
                  "item_name,"
                  "specs,"
                  "unit_price,"
                  "qty,"
                  "pack_qty,"
                  "price_unit,"
                  "mo_order,"
                  "oper_date)";
             sq += " values (";
             sq += "'" + recipe_no + "',";
             sq += "'" + mpPatientInfo["clinic_code"] + "',";
             sq += "'" + mpPatientInfo["card_no"] + "',";
             sq += "'" + pub::usr_code + "',";
             sq += "'" + pub::dp_code + "',";
             sq += "'" + qrm->value("item_code").toString() + "',";
             sq += "'" + qrm->value("item_name").toString() + "',";
             sq += "'" + qrm->value("specs").toString() + "',";
             sq += qrm->value("price").toString() + ",";
             sq += qrm->value("qty").toString() +"*" + qrm->value("pack_qty").toString() + ",";
             sq += qrm->value("PACK_QTY").toString() + ",";
             sq += "'" + qrm->value("QTY_UNIT").toString() + "',";
             sq += "'" + recipe_item_id + "',";
             sq += "sysdate";
             sq += ")";

             sqls << sq;
         }

        sq = "oinsert into fin_opb_feedetail"
             " (recipe_no,sequence_no,trans_type,item_code,item_name,invoice_seq,"
             "mo_order, comb_no,recipe_seq)";
        sq += " values ('" + recipe_no + "',";
        sq += QString::number(sequence_no) + ",'1',";
        sq += "'" + qrm->value("item_code").toString() + "',";
        sq += "'" + qrm->value("item_name").toString() + "','NULL',";
        sq += "'" + recipe_item_id + "','" + comb_no + "','" + recipe_seq + "'";
        sq += ")";

        sqls << sq;
        sqlMsg << qrm->value("item_name").toString() << " 插入表 fin_opb_feedetail。。。";

        //DOSE_MODEL_CODE,SELF_MADE,FEE_CODE,CLASS_CODE,BASE_DOSE,FREQUENCY_CODE,USAGE_CODE,USE_NAME

        sq = "oupdate fin_opb_feedetail set ";
        sq += "CLINIC_CODE = '" + mpPatientInfo["clinic_code"] + "',";           // 门诊号"
        sq += "CARD_NO = '" + mpPatientInfo["card_no"] + "',";                   //病历卡号
        sq += "REG_DATE = to_date('" + mpPatientInfo["reg_date"] + "','yyyy-mm-dd HH24:mi:ss'),";     //挂号日期
        sq += "REG_DPCD = '" + mpPatientInfo["dept_code"] + "',";       //挂号科室代码
        sq += "DOCT_CODE = '" + pub::usr_code + "',";   //开方医师
        sq += "DOCT_DEPT = '" + pub::dp_code + "',";    //开方医师所在科室
        sq += "DRUG_FLAG = '" + qrm->value("item_type").toString() + "',";       // 1西药中成药 2耗材 3诊疗 4草药
        sq += "SPECS = '" + qrm->value("specs").toString() + "',";               // 规格
        sq += "SELF_MADE = '" + qrm->value("SELF_MADE").toString() + "',";       // 自制药标志
        sq += "DRUG_QUALITY = '" + qrm->value("drug_quality").toString() + "',"; // 药品性质，麻药，普药
        sq += "DOSE_MODEL_CODE = '" + qrm->value("DOSE_MODEL_CODE").toString() + "',";      // 剂型
        sq += "FEE_CODE = '" + qrm->value("FEE_CODE").toString() + "',";         //  最小费用代码
        sq += "CLASS_CODE = '" + qrm->value("CLASS_CODE").toString() + "',";     // 系统类别
        sq += "UNIT_PRICE = '" + qrm->value("price").toString() + "',";          //  单价
        //sq += "DAYS = '1',";               //  草药的付数，其他药品使用天数
        QString days;
        if(qrm->value("recipe_days").toInt() < 1)
        {
            days = "1";
        }else{
            days = qrm->value("recipe_days").toString();
        }

        sq += "DAYS = " + days + ","; //  草药的付数，其他药品使用天数

        //"qty = qty * days "   //药品数量
        //"amount = price * qty * days ";   //金额

        if(qrm->value("FEE_CODE").toString() == "003")
        {
            //草药
            sq += "QTY = " + qrm->value("qty").toString() + "*" + days + ","; //  数量
            sq += "OWN_COST = " + qrm->value("amount").toString() + "*" + days + ",";   //  现金金额
        }
        else
        {
            sq += "QTY = " + qrm->value("qty").toString() +"*" + qrm->value("pack_qty").toString() + ","; //  数量
            sq += "OWN_COST = " + qrm->value("amount").toString() + ",";   //  现金金额
        }

        sq += "FREQUENCY_CODE = '" + pub::getDicC("频次", qrm->value("frequency").toString()) + "',"; // 频次代码
        sq += "USAGE_CODE = '" + qrm->value("usage_code").toString() + "',"; // 用法代码
        sq += "USE_NAME = '" + qrm->value("usages").toString() + "',";           //  用法名称
        sq += "INJECT_NUMBER = '0',";      //  院内注射次数
        sq += "EMC_FLAG = '0',";           //  加急标记:1普通/2加急
        sq += "LAB_TYPE = '',";            // 样本类型
        sq += "CHECK_BODY = '',";          //  检体
        sq += "DOSE_ONCE = '" + qrm->value("once_dose").toString() + "',";       //  每次用量
        sq += "DOSE_UNIT = '" + qrm->value("dose_unit").toString() + "',";       //  每次用量单位
        sq += "BASE_DOSE = '" + qrm->value("BASE_DOSE").toString() + "',";       //  基本剂量
        sq += "PACK_QTY = '" + qrm->value("PACK_QTY").toString() + "',";         // 包装数量
        sq += "PRICE_UNIT = '" + qrm->value("QTY_UNIT").toString() + "',";      //  计价单位
        sq += "PUB_COST = 0,";             // 可报效金额	                  0.00, --  可报效金额
        sq += "PAY_COST = 0,";             //  自付金额	                  0.00, --  自付金额



        sq += "EXEC_DPCD = '" + qrm->value("exe_deptcode").toString() + "',";        // 执行科室代码
        sq += "EXEC_DPNM = '" + getDeptName(qrm->value("exe_deptcode").toString()) + "',";       // 执行科室名称
        sq += "CENTER_CODE = '" + qrm->value("center_code").toString()  + "',";         //  医保中心项目代码
        sq += "ITEM_GRADE = '0" + qrm->value("center_grade").toString() + "',";          //  项目等级，01甲类，02乙类，03丙类
        sq += "MAIN_DRUG = '0',";          // 主药标志
        sq += "OPER_CODE = '" + pub::usr_code + "',";   // 划价人
        sq += "OPER_DATE = sysdate,";      //  划价时间
        sq += "PAY_FLAG = '0',";           // 收费标志，1未收费，2收费
        sq += "CANCEL_FLAG = '1',";        // 作废标志,1未作废,2作废
        sq += "FEE_CPCD = '',";            //  收费员代码
        sq += "FEE_DATE = to_date('0001-01-01 00:00:00','yyyy-mm-dd HH24:mi:ss'),";    // 收费日期
        sq += "INVOICE_NO = '',";          //  票据号
        sq += "INVO_CODE = '',";           // 发票科目代码
        sq += "INVO_SEQUENCE = '',";       //  发票内流水号
        sq += "CONFIRM_FLAG = '0',";       // 1未确认/2确认
        sq += "CONFIRM_CODE = '',";        // 确认人
        sq += "CONFIRM_DEPT = '',";        //  确认科室
        sq += "CONFIRM_DATE = to_date('0001-01-01 00:00:00','yyyy-mm-dd HH24:mi:ss'),";     // 确认时间
        sq += "NEW_ITEMRATE = '0',";       //  '0',
        sq += "OLD_ITEMRATE = '0',";       //'0',
        sq += "EXT_FLAG = '',";            //  '',
        sq += "PACKAGE_CODE = '" + qrm->value("package_code").toString() + "',";        //  '',
        sq += "PACKAGE_NAME = '" + qrm->value("package_name").toString() + "',";        // '',
        sq += "EXT_FLAG1 = '',";           //  '',
        sq += "EXT_FLAG2 = '',";           //  '',
        sq += "EXT_FLAG3 = '1',";          // '1',1 包装 单位 0, 最小单位
        sq += "NOBACK_NUM = " + qrm->value("qty").toString()  +"*" + qrm->value("pack_qty").toString() +  ",";//  可退数量
        sq += "CONFIRM_NUM = 0,";          //  '0',
        sq += "CONFIRM_INJECT = '0',";     // '0',
        sq += "ECO_COST = 0,";             // 优惠金额[58]
        sq += "over_cost = 0,";            //超标金额
        sq += "EXCESS_COST = 0,";          //药品超标金额
        sq += "DRUG_OWNCOST = 0,";         //附材标志
        sq += "COST_SOURCE = '1',";        //	费用来源 0 操作员 1 医嘱 2 终端 3 体检
        sq += "SUBJOB_FLAG = '0',";        //'0',
        sq += "ACCOUNT_FLAG = '0',";       //0没有扣账户 1 已经扣账户
        sq += "UPDATE_SEQUENCENO = '0',";  //更新库存的流水号(物资)
        sq += "doctindept = '" + pub::dp_code + "',";   //医生所属科室
        sq += "MEDICALGROUPCODE = '',";    //   医疗组	'',
        sq += "ACCOUNT_NO = ''";          //门诊一卡通账号
        sq += " WHERE mo_order = '" + recipe_item_id + "'";
        sqls << sq;
        sqlMsg << qrm->value("item_code").toString() << " 更新表 fin_opb_feedetail。。。";

        // 非空字段：看诊序号 see_no，医嘱流水号 sequence_no
        //同时插入其它字段：处方内流水 recipe_seq,完整流水sort_id,处方号 recipe_no，
        //项目编码 item_code，项目名称 item_name，收费序列号 recipe_feeseq,处方号，组合号
        sq = "oinsert into met_ord_recipedetail (see_no,sequence_no,"
             " recipe_seq, sort_id, item_code, item_name, recipe_feeseq, recipe_no,comb_no)";
        sq += " values ('" + see_no + "','" + recipe_item_id + "',";
        sq += QString::number(sequence_no) + "," + QString::number(sort_id) + ",";
        sq += "'" + qrm->value("item_code").toString() + "',";
        sq += "'" + qrm->value("item_name").toString() + "','" + recipe_seq + "',";
        sq += "'" + recipe_no + "', '" + comb_no + "'";
        sq += ")";

        sqls << sq;
        sqlMsg << qrm->value("item_name").toString() << " 插入表 met_ord_redipedetail。。。";

        sq = "oupdate met_ord_recipedetail set ";
        sq += "clinic_code = '" + mpPatientInfo["clinic_code"] + "',";                 // 门诊号"
        sq += "card_no = '" + mpPatientInfo["card_no"] + "',";                         //病历卡号
        sq += "reg_date = to_date('" + mpPatientInfo["reg_date"] + "','yyyy-mm-dd HH24:mi:ss'),"; //挂号日期
        sq += "dept_code = '" + qrot->value("dept_code").toString() + "',";            //挂号科室代码
        sq += "specs = '" + qrm->value("specs").toString() + "',";                     // 规格
        sq += "drug_flag = '" + qrm->value("item_type").toString() + "',";             // 1西药中成药 2耗材 3诊疗 4草药
        sq += "class_code = '" + qrm->value("CLASS_CODE").toString() + "',";           // 系统类别
        sq += "fee_code = '" + qrm->value("FEE_CODE").toString() + "',";               //  最小费用代码
        sq += "unit_price = '" + qrm->value("price").toString() + "',";                //  单价
        //sq += "days = '1',";                 //  草药的付数，其他药品为1
        sq += "DAYS = " + days + ","; //  草药的付数，其他药品使用天数

        if(qrm->value("FEE_CODE").toString() == "003")
        {
            //草药
            sq += "QTY = " + qrm->value("qty").toString() + "*" + days + ","; //  数量
            sq += "OWN_COST = " + qrm->value("amount").toString() + "*" + days + ",";   //  现金金额
        }
        else
        {
            sq += "qty = '" + qrm->value("qty").toString() + "',";                         //  数量
            sq += "own_cost = " + qrm->value("amount").toString() + ","; //  现金金额
        }

        sq += "pack_qty = '" + qrm->value("PACK_QTY").toString() + "',";               // 包装数量
        sq += "item_unit = '" + qrm->value("QTY_UNIT").toString() + "',";             //  计价单位
        sq += "pay_cost = 0,";               //  自负金额
        sq += "pub_cost = 0,";               //  报销金额
        sq += "base_dose = '" + qrm->value("BASE_DOSE").toString() + "',";             //  基本剂量
        sq += "self_made = '" + qrm->value("SELF_made").toString() + "',";             // 自制药标志
        sq += "drug_quanlity = '" + qrm->value("drug_quality").toString() + "',";      // 药品性质，麻药，普药
        sq += "once_dose = '" + qrm->value("once_dose").toString() + "',";             //  每次用量
        sq += "once_unit = '" + qrm->value("dose_unit").toString() + "',";             //  每次用量单位
        sq += "dose_model_code = '" + qrm->value("DOSE_MODEL_CODE").toString() + "',"; // 剂型
        sq += "frequency_code = '" + pub::getDicC("频次", qrm->value("frequency").toString()) + "',"; // 频次代码
        sq += "frequency_name= '" + qrm->value("frequency").toString() + "',";         //   --频次名称
        sq += "usage_code = '" + qrm->value("usage_code").toString() + "',"; // 用法代码
        sq += "usage_name = '" + qrm->value("usages").toString() + "',";        //  用法名称
        sq += "english_ab = '',";     //   --用法英文缩写
        if(qrm->value("exe_deptcode").toString().isEmpty())
        {
            QMessageBox::information(this, "注意", "项目 " + qrm->value("item_name").toString() + " 执行科室信息缺失！");
            return;
        }
        sq += "exec_dpcd = '" + qrm->value("exe_deptcode").toString() + "',";       // 执行科室代码 ? 处方科室代码
        sq += "exec_dpnm = '" + getDeptName(qrm->value("exe_deptcode").toString()) + "',";   // 执行科室名称 ? 处方科室名称
        //sq += "exec_dpcd = '" + pub::dp_code + "',";       // 执行科室代码 ? 处方科室代码
        //sq += "exec_dpnm = '" + pub::dp_name + "',";   // 执行科室名称 ? 处方科室名称
        sq += "main_drug = '0',";     // 主药标志
        sq += "hypotest =  '1',";     // 1不需要皮试/2需要皮试，未做/3皮试阳/4皮试阴
        sq += "inject_number = '0',"; // 院内注射次数
        sq += "remark  = '',";        // 备注
        sq += "doct_code = '" + pub::usr_code + "',";      //开方医师
        sq += "doct_name = '" + pub::usr_name + "',";      //开方医师
        sq += "doct_dpcd = '" + pub::dp_code + "',";       //开方医师所在科室
        sq += "oper_date = sysdate,"; //  开立时间
        sq += "status = '0',";        //  处方状态,0开立，1收费，2确认，3作废,4撤销
        sq += "cancel_userid =  '',"; //作废人
        sq += "cancel_date = to_date('0001-01-01 00:00:00','yyyy-mm-dd HH24:mi:ss'), "; //  --作废时间
        sq += "emc_flag = '0',";                                       //  --加急标记0普通/1加急
        sq += "lab_type = '',";                                        //     --样本类型
        sq += "check_body = '',";                                      //   --检体
        sq += "apply_no = '',";                                        //  --申请单号
        sq += "subtbl_flag = '0',";                                    //   '0',   --0没有附材/1带附材/2是附材
        sq += "need_confirm = '0',";                                   //    --是否需要确认，1需要，0不需要
        sq += "confirm_code = '',";                                    //  --确认人
        sq += "confirm_dept = '',";                                    //   --确认科室
        sq += "confirm_date = to_date('0001-01-01 00:00:00','yyyy-mm-dd HH24:mi:ss'),";//     --确认时间
        sq += "charge_flag = '0',";                                    // --0未收费/1收费
        sq += "charge_code = '',";                                     //  --收费员
        sq += "charge_date  = to_date('0001-01-01 00:00:00','yyyy-mm-dd HH24:mi:ss'),"; //   --收费时间
        sq += "phamarcy_code = '" + qrm->value("exe_deptcode").toString() + "',";//        取药药房
        sq += "MINUNIT_FLAG = '0',";                                   // --最小单位标记
        sq += "ordertype = '0',";                                      // ,--医嘱类型
        sq += "subcombno = '',";                                       //
        sq += "RESUMEORDER = '',";                                     //
        sq += "PASS_FLAG = '',";                                       //
        sq += "mark1 = '',"; //
        sq += "mark2 = '',"; //
        sq += "mark3 = '',"; //
        sq += "CLINICDIAG_CODE = '" + qrm->value("diag1c").toString() + "',";       //主诊断编码
        sq += "CLINICDIAG_NAME = '" + qrm->value("diag1").toString() + "',";        //主诊断名
        sq += "CLINICOTHERDIAG1_CODE = '" + qrm->value("diag2c").toString() + "',"; //
        sq += "CLINICOTHERDIAG1_NAME = '" + qrm->value("diag2").toString() + "',";  //
        sq += "CLINICOTHERDIAG2_CODE = '" + qrm->value("diag3c").toString() + "',"; //
        sq += "CLINICOTHERDIAG2_NAME = '" + qrm->value("diag3").toString() + "',";  //
        sq += "CLINICZYDIAG_CODE= '',";   //   中医诊断
        sq += "CLINICZYDIAG_NAME= '',";   //
        sq += "CASE1 = '',";               //
        sq += "CASE2 = '',";  //
        sq += "TIMEOFONSET1 = to_date('0001-01-01 00:00:00','yyyy-mm-dd HH24:mi:ss'),";
        sq += "TIMEOFONSET2 = to_date('0001-01-01 00:00:00','yyyy-mm-dd HH24:mi:ss'),";
        sq += "OCCUPATION = '',"; //
        sq += "YNFR = ''";        //

        sq += " WHERE sequence_no = '" + recipe_item_id + "'";
        sqls << sq;
        sqlMsg << qrm->value("item_code").toString() << " 更新表 met_ord_redipedetail。。。";

        exec_dpcd = qrm->value("exe_deptcode").toString();        //更新执行科室
        drug_quality = qrm->value("drug_quality").toString(); //更新药品属性
        item_type = qrm->value("item_type").toString(); //更新项目属性
        sequence_no++;
    }

    sqlMsg << "发生错误，正在回滚数据。。。";
    qDebug()<<"sqls will send to thread process : "<<sqls;

    sqlThread->setSqls(sqls);

    sqlThread->start();
    dlgDelay->setNeedClose(false);
    dlgDelay->exec();

    if(sqlThread->getLastError())
    {
        //sql语句执行遇到错误
        return;
    }

    if(mpPatientInfo["pact_code"] == "2" && ui->rb_reci_ct_insu->isChecked())
    {
        //医保处方且按医保收费，进行医保事中校验
        //3101校验依赖前一步生成的 met_ord_recipedetail 中的数据

        dlgDelay->setText("正在进行医保处方校验。。。");
        dlgDelay->setModal(true);
        dlgDelay->setNeedClose(false);
        dlgDelay->show();
        qApp->processEvents();

        busi_continue = true;
        on_pbCheck3101_clicked();

        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();

        if(!busi_continue)
        {
            //事中校验异常，用户选择返回重新编辑处方
            on_pbEditAgain_clicked();
            return;
        }
    }

    save_senior_recipe_no();//处理超职级药品信息
    save_medical_plan(); //保存诊疗计划

    if(ui->rb_reci_ct_insu->isChecked())
    {
        save_5465("1");//保存记录
        //push_5465();
    }

    on_pbFresh_clicked();

}

void Form_ys_bzgl::save_senior_recipe_no()
{
    QString clinic_code = mpPatientInfo["clinic_code"];
    QStringList reci_lst;

    sq = " select distinct item_code "
         " from pha_sto_recipe_senior_check"
         " where "
         " clinic_code = '%1' and check_status = '0' and apply_doct_code = '%2' ";//and recipe_no = '0'
    sq = sq.arg(clinic_code).arg(pub::usr_code);
    qDebug()<<"提取需要审批的项目编码："<<sq<<"\n";
    qro->exec(sq);

    bool has_senior = false;
    while(qro->next())
    {
        has_senior = true;

        reci_lst.clear();
        sq = " select recipe_no from met_ord_recipedetail "
             " where clinic_code = '%1' and item_code = '%2' and status = '0'";
        sq = sq.arg(clinic_code).arg(qro->value(0).toString());
        qDebug()<<"提取需要审批的处方号："<<sq<<"\n";
        qrot->exec(sq);

        while(qrot->next())
        {
            reci_lst << qrot->value(0).toString();
        }

        if(reci_lst.size() > 0)
        {
            sq = " update pha_sto_recipe_senior_check set recipe_no = '%1'"
                 " where clinic_code = '%2' and check_status = '0'";
            sq = sq.arg(reci_lst.join("^")).arg(clinic_code);
            qDebug()<<"保存需要审批项目的处方号："<<sq<<"\n";
            qrot->exec(sq);
        }
        else
        {
            has_senior = false;
        }
    }

    if(has_senior)
    {
        //登记签字消息
        sq = "insert into com_events"
             " (event_id, event_user,send_date,event_sendder,user_dept,clinic_code)"
             " values"
             "('out_grade_apply', '%1',sysdate,'%2','%3','%4')";
        sq = sq.arg(pub::dr_senior)//send to
                .arg(pub::usr_code)
                .arg(pub::dp_code)
                .arg(clinic_code);
        qDebug()<<"登记审核消息："<<sq<<"\n";
        qrot->exec(sq);
    }
    else
    {
        //清除可能存在的登记消息
        sq = "delete from com_events"
             " where "
             " event_id = 'out_grade_apply'"
             " and event_user = '%1'"
             " and event_sendder = '%2'"
             " and user_dept = '%3'"
             " and clinic_code = '%4'";
        sq = sq.arg(pub::dr_senior)//send to
                .arg(pub::usr_code)
                .arg(pub::dp_code)
                .arg(clinic_code);
        qDebug()<<"变更超职级审核消息推送："<<sq<<"\n";
        qrot->exec(sq);

        sq = " update pha_sto_recipe_senior_check set check_status = '3' "
             " where  "
             " clinic_code = '%1'"
             " and check_status = '0' and apply_doct_code = '%2' ";//and recipe_no = '0'
        sq = sq.arg(clinic_code).arg(pub::usr_code);
        qDebug()<<"变更超职级登记记录："<<sq<<"\n";
        qrot->exec(sq);
    }

}
void Form_ys_bzgl::save_medical_plan()
{
    QString med_plan;

    qDebug()<<"提取治疗计划，检索医师处方内容";
//    QString  cur_date, cur_bzh;
    sq=" select ITEM_NAME,sum(qty) qty,item_unit,FEE_CODE," // distinct
       " max(ONCE_DOSE) ONCE_DOSE, max(ONCE_UNIT) ONCE_UNIT, "
       " max(FREQUENCY_NAME) FREQUENCY_NAME, max(USAGE_NAME) USAGE_NAME"
       " from met_ord_recipedetail"
       " where clinic_code='"
            + mpPatientInfo["clinic_code"]
            + "' and status not in('3','4') "
              " and fee_code in('001','002','003','005')"
              " group by item_name,item_unit,fee_code"
              " order by fee_code";
    //fee_code :
    //001 西药 ， 002 中药 , 004 化验 ，007 检查
    //005 处置 ， 006 留观费 ，010 器械
    //011 采血费， 012 彩色打印照片, 014 取暖费 ，022 床位费（床）

    qDebug()<<sq<<"\n";

    if(!qro->exec(sq))
    {
        qDebug()<<qro->lastError().text();
        return;
    }

    if(!qro->next())
    {
        qDebug()<< "找不到指定检索信息关联的医师处方内容！";
    }

    bool has_herb = false; //处方是否有草药
    QString herb_usage = "";//草药用法
    while(true)
    {
        int fee_code = qro->value("fee_code").toInt();
        QString s;

        if( fee_code == 1 || fee_code == 2 )
        {
            // 西药，中成药
            s.append(qro->value("ITEM_NAME").toString()
                     +" "
                     +qro->value("QTY").toString()
                     +qro->value("ITEM_UNIT").toString());
            s.append(" , ");
            s.append(qro->value("USAGE_NAME").toString());
            s.append(" , ");
            s.append(qro->value("ONCE_DOSE").toString());
            s.append(qro->value("ONCE_UNIT").toString());
            s.append("/");
            s.append(qro->value("FREQUENCY_NAME").toString());
            s.append("; ");
            med_plan.append(s);

        }
        else if( fee_code == 3)
        {
            //草药
            has_herb = true;
            s.append(qro->value("ITEM_NAME").toString());
            s.append(" ");
            s.append(qro->value("QTY").toString());
            s.append(qro->value("ITEM_UNIT").toString());
            s.append("  ");

            herb_usage = qro->value("USAGE_NAME").toString();
            herb_usage.append("  ");
            herb_usage.append(qro->value("ONCE_DOSE").toString());
            herb_usage.append(qro->value("ONCE_UNIT").toString());
            herb_usage.append("/");
            herb_usage.append(qro->value("FREQUENCY_NAME").toString());
            herb_usage.append("; ");
            med_plan.append(s);
        }
        else if( fee_code == 5)
        {
            //处置
            s.append(qro->value("ITEM_NAME").toString());
            s.append(" ");
            s.append(qro->value("QTY").toString());
            s.append(qro->value("ITEM_UNIT").toString());
            s.append(" ; ");
            med_plan.append(s);
        }

        if(!qro->next()){
            break;
        }
    }

    QString str_sm3 = cur_sm3("database", med_plan);

    sq = " select medical_plan from ys_bz_e_rec e "
         " where clinic_code = '" + mpPatientInfo["clinic_code"] + "' ";
    qDebug()<<"提取旧的诊疗计划 ："<<sq<<"\n";
    qrm->exec(sq);
    QString plan_old = "";
    if(qrm->next())
    {
        plan_old = qrm->value(0).toString();
    }

    QString tmstmp = QString::number(QDateTime::currentDateTime().toMSecsSinceEpoch());

    save_rec_hist("诊疗计划", med_plan, plan_old, tmstmp, mpPatientInfo["clinic_code"]);
qDebug()<<"str_sm3:"<<str_sm3<<"\n";
    sq = " update ys_bz_e_rec e set tmstmp = now(),"
         " medical_plan = '" + med_plan + "',";
    sq += " sm3 = '" + str_sm3 + "'";
    sq += " where clinic_code = '" + mpPatientInfo["clinic_code"] + "' ";
    qDebug()<<"修改保存病志记录-medecal advice ："<<sq<<"\n";
    qrm->exec(sq);

    sq = "insert into ys_bz_e_rec_sm3 (tmstmp, tmstmp_count, sm3_code, clinic_code)"
         " values(now(), %1, '%2', '%3')" ;
    sq = sq.arg(tmstmp)
            .arg(str_sm3)
            .arg(mpPatientInfo["clinic_code"]);
    qDebug()<<"save ys_bz_e_rec_sm3 : "<<sq<<"\n";
    qrm->exec(sq);

}

void Form_ys_bzgl::on_pbClear_clicked()
{

    initialFinished = false;  //防止触发界面事件

    ui->leName->clear();
    ui->leGend->clear();
    ui->leAge->clear();
    ui->lePhone->clear();
    ui->leIdenno->clear();
    ui->lePatientType->clear();
    ui->leCardNo->clear();
    ui->leNameS->clear();
    ui->leIdennoS->clear();
    ui->le_current_date->clear();
    ui->le_current_doct->clear();

    ui->ckb_no_own->setChecked(false);

    mpPatientInfo.clear();

    ui->ckb_final_diag->setChecked(true);

    on_pb_clear_base_clicked();  //清除基本内容
    tvRecipeNewRefresh(1);      //清除处方内容

    ui->tvHistory->setModel(NULL);
    ui->tabWidget->setCurrentIndex(0);

    ui->tab_recipe_new->setEnabled(false);
    ui->tab_history->setEnabled(false);
    ui->tab_base->setEnabled(false);
    ui->tab_recipe_today->setEnabled(false);
    ui->tab_aux_check->setEnabled(false);

    md_pics->setQuery(NULL);

    pic_num = 0;
    pic_describe.clear();
    ui->le_pic_describe->clear();
    ui->le_pic_desc->clear();

    if(camera != nullptr)
    {
        camera->stop();
        camera->unload();
        delete camera;
        camera = nullptr;
    }

    if(viewfinder != nullptr)
    {
        delete viewfinder;
        viewfinder = nullptr;
    }

    if(imageCapture != nullptr)
    {
        delete imageCapture;
        imageCapture = nullptr;
    }

    camera_initialized = false;

    initialFinished = true;

    //ui->rb_last_date->setChecked(true);

}

QString Form_ys_bzgl::getIcpcCode(QString s)
{
    if(s.isEmpty())
    {
        return "";
    }
    qrmt->exec("select icpc_code from com_dict_icpc where item_name ='" + s + "' ");
    qrmt->next();
    return(qrmt->value(0).toString());
}

QString Form_ys_bzgl::getNatCode(QString s, QString type)
{

    //type : 0,就诊原因  1,治疗、处置、化验等 2,诊断 3,药品 8,中医诊断 9,中医症候

    if(s.isEmpty())
    {
        return "";
    }
    QString tmp_sql = "select nat_code from com_dict_icpc where nat_code <>'' "
                      "and item_name ='" + s + "' and type = '" + type + "'";
    qrmt->exec(tmp_sql);
    qrmt->next();

    return(qrmt->value(0).toString());
}

void Form_ys_bzgl::on_tvList_doubleClicked(const QModelIndex &index)
{
    on_tvList_clicked(index);
}

void Form_ys_bzgl::on_tvHistory_clicked(const QModelIndex &index)
{
    QString t = "" ;

    if(ui->rbOut->isChecked())  //远程查询
    {
        t = index.siblingAtColumn(5).data().toString();
        t += "\n" + last_hospital_info;
    }
    else        //本地查询
    {
        QString clinic_code = index.siblingAtColumn(7).data(0).toString();

        sq = "select xmmc,xmjg from ys_bz_e_lib where clinic_code = '" + clinic_code + "'";
        qrmt->exec(sq);
        QString str_lib;
        if(qrmt->next())
        {
            str_lib = "检查化验：" + qrmt->value(0).toString() +"/"+ qrmt->value(1).toString() + "\n";
        }

        sq = "select * from ys_bz_e_rec r where clinic_code = '" + clinic_code + "'";

        qDebug()<<"提取历史诊断记录："<<sq;

        qrmt->exec(sq);
        if(qrmt->next())
        {
            t.append("患者主诉：" + qrmt->value("hzzs").toString() + "\n");   //主诉;
            t.append("现病史:" + qrmt->value("xbs").toString() + "\n");     //现病史;
            t.append("既往史：" + qrmt->value("jws").toString() + "\n");     //既往史
            t.append("过敏史：" + qrmt->value("gms").toString() + "\n");     //过敏史;
            t.append("个人史：" + qrmt->value("person_hist").toString() + "\n");     //个人史;
            t.append("家族史：" + qrmt->value("family_hist").toString() + "\n");     //家族史;
            t.append("体格检查：" + qrmt->value("tgjc").toString() + "\n");   //体格检查;

            bool is_tr = false;
            if(!qrmt->value("zyzd1").toString().isEmpty())     //中医诊断
            {
                is_tr = true;
            }

            if(is_tr)
            {
                t.append("中医查体:" + qrmt->value("tgjc_tr").toString() + "\n");   //中医查体
                t.append("中医辩证:" + qrmt->value("zybz").toString() + "\n");   //中医辩证
                t.append("中医类证鉴别:" + qrmt->value("similar_syndrom").toString() + "\n");   //中医辩证
                t.append("中医治则:" + qrmt->value("treat_tr").toString() + "\n");   //中医辩证
            }

            if(!str_lib.isEmpty())
            {
                t.append(str_lib);
            }

            QString zyzd,xyzd;  //中医诊断，西医诊断

            if(!qrmt->value("zyzd1").toString().isEmpty())
            {
                zyzd = qrmt->value("zyzd1").toString() + "." + qrmt->value("zyzh1").toString() ;
            }

            if(!qrmt->value("zyzd2").toString().isEmpty())
            {
                zyzd += " / " + qrmt->value("zyzd2").toString() + "." + qrmt->value("zyzh2").toString() ;
            }

            if(!qrmt->value("zyzd3").toString().isEmpty())
            {
                zyzd += " / " + qrmt->value("zyzd3").toString() + "." + qrmt->value("zyzh3").toString() ;
            }

            xyzd = qrmt->value("zd1").toString();    //西医诊断至少有一个

            if(!qrmt->value("zd2").toString().isEmpty()){
                xyzd.append(" / " + qrmt->value("zd2").toString());
            }

            if(!qrmt->value("zd3").toString().isEmpty()){
                xyzd.append(" / " + qrmt->value("zd3").toString());
            }

            t.append("西医诊断：" + xyzd + "\n");
            if(is_tr)
            {
                t.append("中医诊断：" + zyzd + "\n");
            }

            if(!qrmt->value("yz").toString().isEmpty())
            {
                t.append("医嘱:" + qrmt->value("yz").toString() + "\n");         //医嘱
            }
        }

    }

    if(t.isEmpty())
    {
        t = "无关联信息。";
    }

    QMessageBox::information(this, "关联信息" , t);

}

void Form_ys_bzgl::on_leHzzs_returnPressed()
{
    ui->pt_current_symp->setFocus();
}

void Form_ys_bzgl::on_cbbReason_activated(const QString &arg1)
{
    Q_UNUSED(arg1);
    ui->leHzzs->setFocus();
}

void Form_ys_bzgl::on_cbbBzmb_activated(const QString &arg1)
{
    Q_UNUSED(arg1);
    ui->leHzzs->setFocus();
}

void Form_ys_bzgl::on_leJws_returnPressed()
{
    ui->leGms->setFocus();
}

void Form_ys_bzgl::on_leGms_returnPressed()
{
    ui->pt_body_check->setFocus();
}

void Form_ys_bzgl::on_tvHistory_doubleClicked(const QModelIndex &index)
{
    on_tvHistory_clicked(index);
}

void Form_ys_bzgl::on_pbCheck3101_clicked()
{

    QJsonObject in; //入参
    //QJsonObject inpu,inpud; //
    QJsonObject jo_encounter,jo_patient, jo_data;
    QJsonArray ja_ord, ja_diag;
    QJsonObject jsob;
    QJsonDocument jsdoc;    //清空QJsonObject之用

    sq = "select sequence_no rx_id , recipe_no rxno ,item_code hosplist_code, "
         "item_name hosplist_name,qty cnt, "
         " unit_price pric, own_cost sumamt, specs spec,item_unit spec_unt, "
         " to_char(oper_date,'yyyy-mm-dd hh24:mi:ss') drord_begn_date, "
         " exec_dpnm drord_dept_name, dept_code drord_dept_codg ,"
         " doct_code drord_dr_codg, doct_name drord_dr_name"
         " from met_ord_recipedetail "
         " where status = '0' and clinic_code = '" + mpPatientInfo["clinic_code"] + "'";
    qro->exec(sq);
qDebug()<<sq;
    double medfee_sumamt = 0;

    while(qro->next())
    {
        sq = "select list_type hilist_type, med_list_codg hilist_code , "
             " center_name hilist_name,nvl(center_item_grade, '0') hilist_lv,"
             " his_price hilist_pric "
             " from fin_com_compare "
             " where fixmedins_hilist_id = '"+qro->value("hosplist_code").toString()+"'";
        qrot->exec(sq);

        if(qrot->next())
        {
            jsob.insert("rx_id", qro->value("rx_id").toString()); //	处方(医嘱)标识	字符型	50		Y	处方(医嘱)记录唯一ID
            jsob.insert("rxno", qro->value("rxno").toString()); //	处方号	字符型	20		Y
            jsob.insert("long_drord_flag","0"); //	是否为长期医嘱	字符型	3		Y	[1=是,0=否]

            jsob.insert("hilist_type", qrot->value("hilist_type").toString()); //	目录类别	字符型	3	Y	Y	参考字典表,1药品，2服务，3设施，4耗材
            jsob.insert("chrg_type","02"); //	收费类别	字符型	3	Y	Y	参考字典表
            jsob.insert("drord_bhvr","0"); //	医嘱行为	字符型	3	Y	Y	参考字典表
            jsob.insert("hilist_code", qrot->value("hilist_code").toString()); //	医保目录代码	字符型	20		Y	国家统一标准编码
            jsob.insert("hilist_name", qrot->value("hilist_name").toString()); //	医保目录名称	字符型	50		Y	国家统一标准名称
            jsob.insert("hilist_lv", qrot->value("hilist_lv").toString()); //	医保目录等级	字符型	3		Y
            jsob.insert("hilist_pric", QString::asprintf("%.2f", qrot->value("hilist_pric").toDouble())); //	医保目录价格	数值型	16,2		Y

            jsob.insert("hosplist_code", qro->value("hosplist_code").toString()); //	医院目录代码	字符型	20		Y
            jsob.insert("hosplist_name", qro->value("hosplist_name").toString()); //	医院目录名称	字符型	50		Y
            jsob.insert("cnt", qro->value("cnt").toDouble()); //	数量	数值型	6,2		Y
            jsob.insert("pric", QString::asprintf("%.2f",qro->value("pric").toDouble())); //	单价	数值型	16,2		Y
            jsob.insert("sumamt", QString::asprintf("%.2f", qro->value("sumamt").toDouble())); //	总费用	数值型	16,2		Y
            jsob.insert("ownpay_amt",0); //	自费金额	数值型	16,2		Y
            jsob.insert("selfpay_amt",0); //	自付金额	数值型	16,2		Y
            QString s = qro->value("spec").toString();  //	规格	字符型	100		Y	例如:0.25g×12片/盒
            jsob.insert("spec", (s.isEmpty() ? "-" : s)); //过滤空白规格
            jsob.insert("spec_unt", qro->value("spec_unt").toString()); //	数量单位	字符型	20		Y	例如：盒
            jsob.insert("drord_begn_date", qro->value("drord_begn_date").toString()); //	医嘱开始日期	日期型			Y	格式：yyyy-MM-dd HH:mm:ss
            jsob.insert("drord_dept_codg", qro->value("drord_dept_codg").toString()); //	下达医嘱的科室标识	字符型	30		Y
            jsob.insert("drord_dept_name", qro->value("drord_dept_name").toString()); //	下达医嘱科室名称	字符型	50		Y
            //jsob.insert("drord_dr_codg", qro->value("drord_dr_codg").toString()); //	开处方(医嘱)医生标识	字符型	30		Y
            //jsob.insert("drord_dr_name", qro->value("drord_dr_name").toString()); //	开处方(医嘱)医生姓名	字符型	30		Y
            jsob.insert("drord_dr_codg", pub::usr_code); //	开处方(医嘱)医生标识	字符型	30		Y
            jsob.insert("drord_dr_name", pub::usr_name); //	开处方(医嘱)医生姓名	字符型	30		Y
            jsob.insert("drord_dr_profttl", pub::dr_profttl); //	开处方(医嘱)医职称	字符型	3	Y	Y	参考字典表
            jsob.insert("curr_drord_flag","1"); //	是否当前处方(医嘱)	字符型	3		Y	本次处方(医嘱)标记[1=是,0=否]

            medfee_sumamt += qro->value("sumamt").toDouble();

            ja_ord<<jsob;
        }
        else
        {
            continue;
        }
    }

    if(ja_ord.size() < 1)
    {
        QMessageBox::warning(this, "注意", "列表中找不到有效的医保收费项目！");
        return;
    }

    jsob = jsdoc.object();

//    if(ui->cbbDiag1->currentText().isEmpty())
//    {
//        QMessageBox::warning(this, "注意", "没有主诊断！");
//        return;
//    }

    jsob.insert("dise_id", mpPatientInfo["clinic_code"] + "1");//	诊断标识	字符型	50		Y	诊断记录唯一标识
    jsob.insert("inout_dise_type", "2");//出入诊断类别	字符型	3		Y	参考字典表
    jsob.insert("maindise_flag", "1");//主诊断标志	字符型	3		Y	参考字典表
    jsob.insert("dias_srt_no", "1");//诊断排序号	字符型	2		Y	例如：1,2,3…
    jsob.insert("dise_codg", getNatCode(ui->cbbDiag1->currentText(), "2"));//诊断(疾病)编码	字符型	30		Y
    jsob.insert("dise_name", ui->cbbDiag1->currentText());//诊断(疾病)名称	字符型	200		Y
    jsob.insert("dise_date", QDate::currentDate().toString("yyyy-MM-dd"));//诊断日期	日期型	　		Y	格式：yyyy-MM-dd HH:mm:ss

    jo_encounter.insert("dscg_main_dise_codg", jsob["dise_codg"].toString());//	主诊断编码	字符型	20		Y
    jo_encounter.insert("dscg_main_dise_name", jsob["dise_name"].toString());//	主诊断名称	字符型	50		Y


    ja_diag << jsob;

    //if(ui->cbbDiag2->currentIndex() > -1)
    if(!ui->cbbDiag2->currentText().isEmpty())
    {
        jsob.insert("dise_id", mpPatientInfo["clinic_code"] + "2");//	诊断标识	字符型	50		Y	诊断记录唯一标识
        jsob.insert("inout_dise_type", "2");//出入诊断类别	字符型	3		Y	参考字典表
        jsob.insert("maindise_flag", "0");//主诊断标志	字符型	3		Y	参考字典表
        jsob.insert("dias_srt_no", "2");//诊断排序号	字符型	2		Y	例如：1,2,3…
        jsob.insert("dise_codg", getNatCode(ui->cbbDiag2->currentText(), "2"));//诊断(疾病)编码	字符型	30		Y
        jsob.insert("dise_name", ui->cbbDiag2->currentText());//诊断(疾病)名称	字符型	200		Y
        jsob.insert("dise_date", QDate::currentDate().toString("yyyy-MM-dd"));//诊断日期	日期型	　		Y	格式：yyyy-MM-dd HH:mm:ss

        ja_diag << jsob;
    }

    //if(!qrm->value("dise_codg3").isNull() && !qrm->value("dise_codg3").toString().isEmpty())
    if(!ui->cbbDiag3->currentText().isEmpty())
    {

        jsob.insert("dise_id", mpPatientInfo["clinic_code"] + "3");//	诊断标识	字符型	50		Y	诊断记录唯一标识
        jsob.insert("inout_dise_type", "2");//出入诊断类别	字符型	3		Y	参考字典表
        jsob.insert("maindise_flag", "0");//主诊断标志	字符型	3		Y	参考字典表
        jsob.insert("dias_srt_no", "3");//诊断排序号	字符型	2		Y	例如：1,2,3…
        jsob.insert("dise_codg", getNatCode(ui->cbbDiag3->currentText(), "2"));//诊断(疾病)编码	字符型	30		Y
        jsob.insert("dise_name", ui->cbbDiag3->currentText());//诊断(疾病)名称	字符型	200		Y
        jsob.insert("dise_date", QDate::currentDate().toString("yyyy-MM-dd"));//诊断日期	日期型	　		Y	格式：yyyy-MM-dd HH:mm:ss

        ja_diag << jsob;
    }



    jo_encounter.insert("fsi_order_dtos", ja_ord);//处方(医嘱)信息	处方信息集合
    jo_encounter.insert("fsi_diagnose_dtos", ja_diag);//诊断信息DTO	诊断信息集合
    //jo_encounter.insert("fsi_operation_dtos", "[]");//手术操作集合	手术操作集合

    sq = "select insutype from fin_ipr_siinmaininfo where rownum = 1 and inpatient_no = "
         "'"+mpPatientInfo["clinic_code"]+"'";
    qrot->exec(sq);
    qrot->next();
    jo_encounter.insert("insutype", qrot->value(0).toString());//险种	字符型	3	Y	Y	参考字典表

    jo_encounter.insert("medfee_sumamt", QString::asprintf("%.2f",medfee_sumamt));//  总费用
    jo_encounter.insert("ownpay_amt", 0);//	自费金额	数值型	16,2		Y
    jo_encounter.insert("selfpay_amt", 0);//	自付金额	数值型	16,2		Y
    jo_encounter.insert("setl_totlnum", 1);//	结算总次数	数值型	4		Y
    jo_encounter.insert("reim_flag", "1");//	报销标志	字符型	3	Y	Y	参考字典表
    jo_encounter.insert("out_setl_flag", "0");//	异地结算标志	字符型	3	Y	Y	参考字典表
    jo_encounter.insert("med_mdtrt_type", "1");//	就诊类型	字符型	3	Y	Y	参考字典表
    jo_encounter.insert("med_type", "110104");//	医疗类别	字符型	3	Y	Y	参考字典表
    jo_encounter.insert("matn_stas", "0");//	生育状态	字符型	3	Y	Y	参考字典表

    jo_encounter.insert("adm_dept_codg", pub::dp_code);//	入院科室标识	字符型	20
    jo_encounter.insert("adm_dept_name", pub::dp_name);//	入院科室名称	字符型	50
    jo_encounter.insert("dscg_dept_codg", pub::dp_code);//	出院科室标识	字符型	20
    jo_encounter.insert("dscg_dept_name", pub::dp_name);//	出院科室名称	字符型	50

    jo_encounter.insert("dr_codg", pub::dr_codg);//医师编码

    jo_encounter.insert("adm_date", QDate::currentDate().toString("yyyy-MM-dd"));//	入院日期	日期型
    jo_encounter.insert("dscg_date", QDate::currentDate().toString("yyyy-MM-dd"));//	出院日期	日期型

    jo_encounter.insert("medins_name", pub::hos_name); //	医疗机构名称	字符型	200
    jo_encounter.insert("medins_admdvs", pub::hos_insuplc); //	医疗机构行政区划编码	字符型	6
    jo_encounter.insert("medins_type", pub::medins_type); //	医疗服务机构类型	字符型	3
    jo_encounter.insert("medins_lv", pub::medins_lv); //	医疗机构等级	字符型	3

    jo_encounter.insert("mdtrt_id", mpPatientInfo["mdtrt_id"]);//	就诊标识	字符型	50
    jo_encounter.insert("medins_id", pub::hos_ybbh);//	医疗服务机构标识	字符型	50

    jo_patient.insert("fsi_encounter_dtos", jo_encounter);

    jo_patient.insert("patn_id", mpPatientInfo["idenno"]);//参保人标识	字符型	50		Y	参保人唯一ID
    jo_patient.insert("patn_name", mpPatientInfo["name"]);//	姓名	字符型	50		Y
    jo_patient.insert("gend", mpPatientInfo["sex_code"]);//	性别	字符型	3		Y	参考字典表
    jo_patient.insert("brdy", mpPatientInfo["birthday"]);//	出生日期	日期型			Y	格式：yyyy-MM-dd
    jo_patient.insert("poolarea", mpPatientInfo["poolarea"]);//	统筹区编码	字符型	10		Y	参保人所属统筹区
    jo_patient.insert("curr_mdtrt_id", mpPatientInfo["mdtrt_id"]);//	当前就诊标识	字符型	50		Y	本次就诊记录唯一ID
    //jo_patient.insert("fsi_his_data_dto", "");//	医院信息集合	医院信息集合

    jo_data.insert("patient_dtos", jo_patient);//参保人信息	参保人信息集合
    jo_data.insert("syscode", "OwnSoft");//系统编码	字符型
    jo_data.insert("rule_ids","");//	规则标识集合	规则标识集合
    QString task_id = mpPatientInfo["clinic_code"] + "-";
    task_id += QDate::currentDate().toString("yyyyMMdd");
    task_id += QTime::currentTime().toString("HHmmss");
    jo_data.insert("task_id", task_id );//	任务ID	字符型
    jo_data.insert("trig_scen","1");//	触发场景	字符型

    in.insert("data",jo_data);

    QJsonObject jsonRet;    //医保交易返回的Json数据
    QString info;   //如果返回错误，保存错误信息
    remoteQuery = true;
    //if( ! pub::call_business("3101", in, info, jsonRet, "", true , manager, request))
    if( ! pub::call_business("3102", in, info, jsonRet, "", true ,
                             manager, request, mpPatientInfo["clinic_code"]))
    {
        QMessageBox::warning(this, "注意", info);

        //QJsonArray ret = jsonRet.value("output").toObject().value("result").toArray();

        QJsonObject output = jsonRet.value("output").toObject();

        // 交易返回异常 + 存在校验异常结果 = 校验失败
        if( !output.isEmpty())
        {

            QJsonArray result_list = output.value("result").toArray();

            QString jr_id =  result_list[0].toObject().value("jr_id").toString(); //唯一ID

            QStringList para; //唯一ID，规则名称，违规内容

            para << result_list[0].toObject().value("rule_name").toString(); //规则名称
            para << result_list[0].toObject().value("vola_cont").toString(); //违规内容

            pop_3103->prepare_display( para );
            pop_3103->setModal(true);
            pop_3103->exec();

            QList<QMap<QString, QString>> ret_vals = pop_3103->return_values();

            QJsonObject in; //入参
            QJsonObject data; //
            QJsonObject warn_item;
            QJsonArray warns;

            //QJsonDocument jsdoc;    //清空QJsonObject之用

            warn_item.insert("warn_rslt_id", jr_id);
            warn_item.insert("dspo_way", ret_vals[0].value("mode"));
            if(ret_vals[0].value("mode") == "1")
            {
                warn_item.insert("dspo_way_rea", ret_vals[0].value("reason"));
            }


            warns << warn_item;

            data.insert("warn_type", "2");
            data.insert("warns", warns);

            in.insert("data",data);

            QJsonObject jsonRet;    //医保交易返回的Json数据
            QString info;   //如果返回错误，保存错误信息

            if( ! pub::call_business("3103", in, info, jsonRet, "", true ,
                                     manager, request, mpPatientInfo["clinic_code"]))
            {
                QMessageBox::warning(this, "注意", info);

            }

            if (ret_vals[0].value("mode") == "2")
            {
                busi_continue = false;
            }
        }
    }

    remoteQuery = false;

}

void Form_ys_bzgl::on_pbItemClear_clicked()
{
    tvRecipeNewRefresh(0);
}

void Form_ys_bzgl::on_tabWidget_currentChanged(int index)
{

    //qDebug()<<"current idnex is "<<QString::number(index);

    if(!initialFinished)
    {
        return;
    }

    if(remoteQuery)
    {
        ui->tabWidget->setCurrentIndex(0);
        QMessageBox::warning(this, "注意", "正在进行远程查询，请稍候......");
        qApp->processEvents();
        return;
    }

    if(index == 0)
    {
        //history
        ui->tvGroup->setVisible(false);
        pub::setColumnWidth(ui->tvHistory, "0.15^0.15^0.2^0.1^0.05^0.1^0.1", ui->tvHistory->width(), 8);
    }

    if(index == 4 )
    {
        //挂号当日处方
        getRegDateRecipe();
        int w = ui->tvRecipe->width();
        pub::setColumnWidth(ui->tvRecipe, "0.18^0.2^0.05^0.05^0.1^0.1^0.08^0.08^0^0^0^0.05^0.08^0^0^0", w);
        ui->le_left_days->setText("");

    }
    if(index == 3)
    {
        //新开处方
        pub::setColumnWidth(ui->tvRecipeNew, "0.2^0.05^0.08^0.08^0.08^0.08^0.1^0.1^0.1^0.08^0^0^0^0^0^0^0"
                            , ui->tvRecipeNew->width());
        ui->tvList->setVisible(false);
        ui->tvGroup->setVisible(true);
    }
    else
    {
        ui->tvList->setVisible(true);
        ui->tvGroup->setVisible(false);
    }

    if(index == 2)
    {
        display_aux_check();
    }

    if(index == 5)
    {
        if(!camera_initialized)
        {
            camera_initial();
        }
    }

    if(index == 6)
    {
        scene->clear();
        //ui->pb_pic_upload->setEnabled(false);
        on_pb_pic_refresh_clicked();
    }

}

void Form_ys_bzgl::display_aux_check()
{
    //辅助检查//检查化验相关
    sq = "select xmmc 项目名称, xmjg, id, atinc, clinic_code, fee_code, class_code "
         " from ys_bz_e_lib "
         " where clinic_code = '" + mpPatientInfo["clinic_code"] + "'";

    qDebug()<<"//辅助检查//检查化验相关";
    qDebug()<<sq<<"\n";

    md_check->setQuery(sq, pub::db_m);
    ui->tv_aux_check->setModel(md_check);
    pub::setColumnWidth(ui->tv_aux_check, "0.8^0^0^0^0^0", ui->tv_aux_check->width());

    QString result = "";
    qrm->exec(sq);
    while(qrm->next())
    {
        if(!qrm->value(1).toString().isEmpty())
        {
            result.append(qrm->value(0).toString());
            result.append(" : ");
            result.append(qrm->value(1).toString());
            result.append(" ; ");
        }
    }

    ui->pt_all_result->setPlainText(result);
    if(result.isEmpty())
    {
        ui->frm_aux_check->setHidden(true);
        ui->pt_aux_check->clear();
    }
    else
    {
        ui->frm_aux_check->setHidden(false);
        ui->pt_aux_check->setPlainText(result);
    }
}

void Form_ys_bzgl::on_cbName_clicked()
{
    if(!ui->cbName->isChecked())
    {
        ui->leNameS->clear();
    }
}

void Form_ys_bzgl::on_cbCardNo_clicked()
{
    if(!ui->cbCardNo->isChecked())
    {
        ui->leCardNo->clear();
    }
}

void Form_ys_bzgl::on_cbIdenno_clicked()
{
    if(!ui->cbIdenno->isChecked())
    {
        ui->leIdennoS->clear();
    }
}

void Form_ys_bzgl::on_pbModeSave_2_clicked()
{
    QString mb = ui->cbbJchy->currentText().trimmed();
    if(mb.isEmpty()){
        QMessageBox::information(this, "注意", "模板名称不可以为空！");
        return;
    }
    sq="select atinc from ys_bz_e_model where mblx='jy' and mbmc='" + mb + "' and dept_code='"+pub::dp_code+"'";
    qrm->exec(sq);
    if(qrm->next())
    {
        QMessageBox:: StandardButton result= QMessageBox::warning(NULL, "注意", "模板名称已经存在，是否覆盖？",QMessageBox::Yes|QMessageBox::No);
        if(result == QMessageBox::No){
            return;
        }
        sq = "update ys_bz_e_model set jyjg = '" + ui->pt_item_result->toPlainText() + "' where atinc = " + qrm->value(0).toString();
    }
    else
    {
        sq = "insert into ys_bz_e_model (mblx,dept_code,mbmc,jyjg) values(";
        sq += "'jy','"+pub::dp_code+"','"+mb+"','"+ui->pt_item_result->toPlainText()+"')";
    }
    if(qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "模板保存成功！");
    }
}

void Form_ys_bzgl::on_pbModelDelete_2_clicked()
{
    QString mb = ui->cbbJchy->currentText().trimmed();
    if(mb.isEmpty())
    {
        QMessageBox::information(this, "注意", "未指定模板名称！");
        return;
    }

    QMessageBox:: StandardButton result= QMessageBox::warning(this, "注意", "确定要删除指定名称的模板？",QMessageBox::Yes|QMessageBox::No);
    if(result == QMessageBox::No)
    {
        return;
    }

    sq="delete from ys_bz_e_model where mblx='jy' and mbmc='"+mb+"' and dept_code = '" + pub::dp_code + "'";
    qrm->exec(sq);

    QMessageBox::information(this, "注意", "删除完成！");
    ui->cbbJchy->setCurrentIndex(-1);

}

void Form_ys_bzgl::on_cbbJchy_currentIndexChanged(const QString &arg1)
{
    if(!initialFinished) return; //界面初始化未完成
    if(arg1.isEmpty()) return;

    sq = "select mbmc,jyjg from ys_bz_e_model where mblx = 'jy' ";
    sq += " and mbmc = '" + arg1 + "' and dept_code = '" + pub::dp_code + "'";
    qrm->exec(sq);
    qrm->next();

    ui->pt_item_result->setPlainText(qrm->value(1).toString());

}

bool Form_ys_bzgl::saveBZ(int mode)
{
    //保存病志基础信息 ，参数 0 按钮触发， 参数 1 保存处方时调用

    //2024-11-26
    if(!statusCheck("case") )
    {
        if(mode == 1)
        {
            //处方保存模式，校验未通过
            QMessageBox::StandardButton bt;
            bt = QMessageBox::warning(this, "注意", "病志信息不完整，是否忽略错误强行保存？",QMessageBox::Yes|QMessageBox::No);
            if(bt != QMessageBox::Yes)
            {
                return false;
            }
        }
        else
        {
            //病志录入模式，错误直接返回,不保存数据
            return false;
        }
    }

    if( !mpPatientInfo["see_docd"].isEmpty()
            && mpPatientInfo["see_docd"] != pub::usr_code
            && ui->ckb_no_own->isChecked()
            )
    {
        qDebug()<<"非本人接诊记录，可以开具处方，不保存病志！\n";

        //保存最后一次处方时间和上传标志
        sq = " update fin_opr_register set ";
        sq += " upld_flg1 = '0'，" //icpc上传标志
                " receipt_doct_date = sysdate " //最后一次时间
                " WHERE clinic_code = '"
                + mpPatientInfo["clinic_code"] + "'";

        qDebug()<<"保存最后一次处方时间:"<<sq;

        qro->exec(sq);

        return true ;
    }

    //保存初次处方时间
    sq = " update fin_opr_register set ";
    sq += " ynsee = '1', "  //接诊标志
          " see_date = sysdate "//接诊时间
          " WHERE "
          " clinic_code = '"
            + mpPatientInfo["clinic_code"]
            + "' and ynsee = '0' ";

    qDebug()<<"保存初次处方时间和已接诊标志:"<<sq;
    qro->exec(sq);

    //保存最后一次处方时间
    sq = " update fin_opr_register set ";
    sq += " upld_flg1 = '0'," //icpc上传标志
          " receipt_doct_date = sysdate, " //最后一次时间
          " see_docd = '"
            + pub::usr_code
            + "', see_dpcd = '"
            + pub::dp_code
            + "', rela_phone = '"
            + ui->lePhone->text().trimmed()
            + "' WHERE clinic_code = '"
            + mpPatientInfo["clinic_code"] + "'";

    qDebug()<<"保存最后一次处方时间:"<<sq;
    qro->exec(sq);

    //随访记录
    if(!ui->le_next_call->text().trimmed().isEmpty())
    {
        QString id = mpPatientInfo["clinic_code"] ;//每一个预约的唯一标记
        id += "-" + QDate::currentDate().toString("yyyyMMdd");

        sq = "replace into ys_bz_e_call (reg_dept_code, reg_date, clinic_code, book_date,  book_doc, "
             "iden_no, card_no, real_name, wx_name, phone, call_id )"
             " values (";
        sq += "'" + pub::dp_code +"',";
        sq += "'" + mpPatientInfo["reg_date"].left(10) + "', ";
        sq += "'" + mpPatientInfo["clinic_code"] + "', ";
        sq += "  ADDDATE(CURDATE(), " + ui->le_next_call->text() + ") , ";
        sq += "'" + pub::usr_code + "', ";
        sq += "'" + mpPatientInfo["idenno"] + "', ";
        sq += "'" + mpPatientInfo["card_no"] + "', ";
        sq += "'" + mpPatientInfo["name"] + "', ";
        sq += "'" + ui->le_wx_name->text().trimmed() + "', ";
        sq += "'" + ui->lePhone->text().trimmed() + "', ";
        sq += "'" + id + "' ";
        sq += ")";
        qDebug()<<"保存随访记录："<<sq;
        if(!qrm->exec(sq))
        {
            QMessageBox::information(this, "注意", "保存随访记录失败！\nerrmsg : " + qrm->lastError().text());
            return false;
        }
    }

    on_pb_fresh_diag_clicked(); //整理诊断

    if(med_rec())
    {
        if(mode == 0)
        {
            QMessageBox::information(this, "注意", "基础病志信息修改完成！");
        }
        return true;
    }
    else
    {
        return false;
    }
}

void Form_ys_bzgl::on_pbSaveBZ_clicked()
{
    saveBZ(0);
}

void Form_ys_bzgl::on_pbSaveCK_clicked()
{
    QString result = ui->pt_item_result->toPlainText().trimmed();
    QString item_name = ui->le_item_name->text().trimmed();

    if(result.isEmpty() || item_name.isEmpty())
    {
        QMessageBox::information(this, "注意", "项目名称和结果不可以为空！");
        return;
    }

    sq = "select atinc from ys_bz_e_lib where clinic_code = '" + mpPatientInfo["clinic_code"] + "' ";
    sq.append(" and xmmc = '" + item_name + "'");
    qrm->exec(sq);

    if(!qrm->next())
    {
        //外院辅助检查结果，插入新记录
        sq = "insert into ys_bz_e_lib ( jlrq, xmmc, xmjg, clinic_code) "
             "values(  curdate(), ";
        sq += "'" + item_name + "','" + result + "','";
        sq += mpPatientInfo["clinic_code"] + "')";

        if(!qrm->exec(sq))
        {
            QMessageBox::information(this, "注意", "保存辅助检查结果失败！\nerrmsg : " + qrm->lastError().text()+"\nsql : "+sq);
            qDebug()<<sq;
            return;
        }

    }
    else
    {
        //项目名称已经由处方录入，此处补充结果
        QString atinc = qrm->value(0).toString();
        sq = " update ys_bz_e_lib set jlrq = curdate(), xmjg = '" + result + "'";
        sq += " where atinc = '" + atinc + "'";

        if(!qrm->exec(sq))
        {
            QMessageBox::information(this, "注意", "辅助检查结果失败！\nerrmsg : " + qrm->lastError().text()+"\nsql : "+sq);
            return;
        }
    }

    on_tabWidget_currentChanged(2);

}

void Form_ys_bzgl::on_tvGroup_clicked(const QModelIndex &index)
{
    //以组套方式录入处方项目
    if(!statusCheck("base")) return;

    QStandardItem *currentItem = mdGroup->itemFromIndex(index);

    if(currentItem->parent())
    {
        sq = "delete from tmp_group_content";
        qrm->exec(sq);
        QString groupId = index.siblingAtColumn(1).data().toString();
        //QString groupName = index.siblingAtColumn(0).data().toString();

        sq = "select item_name, item_code ,qty ,qty_unit ,"
             " usage_code ,frequency_code , "
             " once_dose, dose_unit,seqid, item_type, exe_deptcode, ext_code"
             " from met_com_groupdetail ";
        sq += " where groupid = '" + groupId + "' order by seqid  ";

        qDebug()<<"select items from group : "<<sq;
        qro->exec(sq);

        int seq = 0;
        QString codes;  //用于判断处方列表是否有重复项
        while(qro->next())
        {
            seq ++ ;
            sq = "insert into tmp_group_content "
                 "(package_name, package_code, item_name, "
                 " item_code, frequency, usages,"
                 " usage_code, once_dose , "
                 " dose_unit,qty, qty_unit,seq,item_type,"
                 " exe_deptcode, ext_code,price,specs,drug_quality,"
                 "DOSE_MODEL_CODE,SELF_made,FEE_CODE,CLASS_CODE,"
                 "BASE_DOSE,pack_qty, center_grade,center_code)";
            sq += " values( '";
            //sq += groupName + "','";
            //sq += groupId + "','";
            sq += qro->value("item_name").toString() + "','";
            sq += qro->value("item_code").toString() + "','";
            sq += qro->value("item_name").toString() + "','";
            sq += qro->value("item_code").toString() + "','";
            codes += ",'" + qro->value("item_code").toString() + "'";
            sq += pub::getDicN("频次", qro->value("frequency_code").toString()) + "','";
            sq += pub::getDicN("给药途径", qro->value("usage_code").toString()) + "','";
            sq += qro->value("usage_code").toString() + "',";
            sq += QString::number(qro->value("once_dose").toDouble()) + ",'";
            sq += qro->value("dose_unit").toString() + "',";
            sq += QString::number(qro->value("qty").toInt()) + ",'";
            sq += qro->value("qty_unit").toString() + "', ";
            sq += QString::number(seq) +",'"; //qro->value("seqid").toString()
            sq += qro->value("item_type").toString() + "','";
            sq += qro->value("exe_deptcode").toString() + "','";
            sq += qro->value("ext_code").toString() + "',";

            if(qro->value("ext_code").toString() == "1")
            {
                //组合项目，明细待插入 tmp_recipe 时再完善
                sq += " 0,'','','','','','','',1,0,'')";
            }
            else
            {
                if(qro->value("item_type").toString() == "1")
                {
                    //药品
                    qrot->exec("select retail_price,specs,drug_quality, "
                               "DOSE_MODEL_CODE,SELF_FLAG,FEE_CODE,CLASS_CODE,BASE_DOSE,pack_qty, valid_state "
                               " from pha_com_baseinfo "
                               " where drug_code = '"+qro->value("item_code").toString()+"'");
                }
                else
                {
                    //非药品
                    qrot->exec("select unit_price, '-','-','-','-',fee_code,sys_class,1,1,valid_state "
                               " from fin_com_undruginfo where item_code "
                               " = '"+qro->value("item_code").toString()+"'");
                }

                qDebug()<<"检查项目有效性："<<qrot->lastQuery();
                qrot->next();
                if(qrot->value("valid_state").toString() !=  "1")
                {
                    QMessageBox::warning(this, "注意", "组套项目 "+qro->value("item_name").toString()+" 已停用！");
                    return;
                }
                sq += qrot->value(0).toString() + ",'" + qrot->value(1).toString() + "','" + qrot->value(2).toString().trimmed() + "','" ;
                sq += qrot->value(3).toString() + "','" + qrot->value(4).toString() + "','" + qrot->value(5).toString().trimmed() + "','" ;
                sq += qrot->value(6).toString() + "'," + qrot->value(7).toString() + ","  + qrot->value(8).toString() + "," ;
                qrot->exec("select center_item_grade, med_list_codg from fin_com_compare "
                           " where fixmedins_hilist_id = '"
                           + qro->value("item_code").toString() + "'");
                qDebug()<<"查询项目医保等级："<<qrot->lastQuery();
                if(qrot->next())
                {
                    if(qrot->value(0).toString().isEmpty())
                    {
                        QString tip = "查询不到 fin_com_compare 中\"" ;
                        tip += qro->value("item_name").toString();
                        tip += "\"的医保等级！";
                        //QMessageBox::information(this, "注意", tip);
                        qDebug()<<tip;
                        sq += "0,''";
                    }
                    else
                    {
                        sq += qrot->value(0).toString();
                        sq += ",'" + qrot->value(1).toString() + "'";
                    }
                }
                else
                {
                    sq += "0,''";
                }

                sq += ")";
            }

            qDebug()<<"插入 tmp_group_content ： "<<sq;

            if(!qrm->exec(sq))
            {
                QMessageBox::information(this, "注意", "插入 tmp_group_content 发生错误 \n" + qrm->lastError().text());
                qDebug()<<"插入 tmp_group_content 发生错误 : " + qrm->lastError().text();
                return;
            }

        }

        sq = "select item_name 项目名称, qty 数量,qty_unit 单位, usages 用法,frequency 频次, concat(once_dose , dose_unit) 用量 "
             "from tmp_group_content  order by seq  ";

        mdGroupPop->setQuery(sq, pub::db_m);

        int w = QApplication::desktop()->width() / 2;
        int h = QApplication::desktop()->height() / 2;
        int t = (QApplication::desktop()->height() - h )/ 2 ;
        int l = (QApplication::desktop()->width() - w )/ 2 ;

        dlgGetValue->setDisplay(*mdGroupPop,QRect(l, t, w, h),"请输入组套数量","0.3^0.1^0.1^0.2^0.2");
        dlgGetValue->setModal(true);
        dlgGetValue->exec();

        QString  popRetStr = dlgGetValue->retStr();

        int count = popRetStr.toInt();
        if(count<1)
        {
            //弹出组套窗口未输入有效数量
            return;
        }

        codes = codes.right(codes.length() -1 );//去除字串头部逗号
        sq = "select item_code from tmp_recipe where item_code in(" + codes + ")";
        qrm->exec(sq);
        if(qrm->next())
        {
            QMessageBox::information(this, "注意", "重复项目已覆盖，如需调整数量请另行操作！");
            //return;
        }

        getDiags(); //读取关联诊断

        sq = "replace into tmp_recipe ("
             "specs, item_name, item_code, frequency, "
             "freq_days, usages, usage_code, "
             "once_dose, dose_unit,qty, "
             "qty_unit,seq,item_type,exe_deptcode , ext_code,"
             "diag1,diag1c,diag2,diag2c,diag3,diag3c,price,"
             "DOSE_MODEL_CODE,SELF_made,FEE_CODE,"
             "CLASS_CODE,BASE_DOSE,pack_qty,drug_quality,"
             "amount, center_grade,center_code, package_name, package_code)"
             " select "
             " specs, item_name, item_code, frequency, "
             " get_freq_days(frequency), "
             " usages, usage_code, once_dose , "
             " dose_unit,qty * "
                + popRetStr + ", qty_unit,seq + "
                + QString::number(newRecipeRecItemCount)
                +" ,item_type,exe_deptcode, ext_code,";
        sq += "'" + diags[0] + "','" + diags[1] + "',";
        sq += "'" + diags[2] + "','" + diags[3] + "',";
        sq += "'" + diags[4] + "','" + diags[5] + "',";
        sq += " price, DOSE_MODEL_CODE, SELF_made, FEE_CODE, CLASS_CODE, BASE_DOSE, pack_qty, drug_quality, ";
        sq += "qty * " + popRetStr + " * price, center_grade,center_code, package_name, package_code";

        sq +=" from tmp_group_content t ";

        qrm->exec(sq);
        qDebug()<<"组套数据插入临时处方表："<<sq;

    }
    tvRecipeNewRefresh(0);
}

void Form_ys_bzgl::tvRecipeNewRefresh(int mode)
{
    //mode 1 清除全部已经录入的处方数据, 然后刷新
    //mode 0 直接刷新

    ui->leSearchG->clear();
    ui->leItemName->clear();
    ui->leSpecs->clear();

    ui->spCnt->setValue(0);
    ui->leUseCnt->clear();
    ui->cbbPackUnit->setCurrentIndex(-1);
    ui->cbbFreq->setCurrentIndex(-1);
    ui->cbbUsage->setCurrentIndex(-1);
    //ui->cbbDoseUnit->setCurrentIndex(-1);
    ui->le_dose_unit->clear();
    //
    ui->cbbExecDept->setCurrentIndex(-1);

    if(mode == 1)   //清除全部已经录入的处方数据
    {
        qrm->exec("delete from tmp_recipe");
    }

    process_combine_item();

    //刷新可用天数
    sq = "update tmp_recipe set recipe_days = qty * (( base_dose * pack_qty ) / once_dose / freq_days )";
    qrm->exec(sq);

    sq = "select item_name 项目名称, "  //0
         "case when center_grade = 1 then '甲' else "
         "( case when center_grade = 2 then '乙' else "
         "( case when center_grade = 3 then '丙' else '' end)end) end 等级, "//1
         " qty 数量,qty_unit 单位, price 价格, amount 金额, usages 用法,frequency 频次, "//2-7
         " concat(once_dose , dose_unit) 用量 , recipe_days 天数,"//8-9
         " specs, once_dose, dose_unit, item_code, exe_deptcode, "//10-14
         " case when item_type ='4' then '中草药' else "
         "   (case when item_type ='1' then '西药中成药' else "
         "      (case when item_type ='2' then '耗材' else '诊疗' end) end) end 类别"//15
         " from tmp_recipe order by seq  ";
    qDebug()<<"显示临时处方内容："<<sq<<"\n";
    mdRecipeNew->setQuery(sq,pub::db_m);
    ui->tvRecipeNew->setModel(mdRecipeNew);

    qrm->exec("select max(seq) from tmp_recipe");
    qrm->next();
    newRecipeRecItemCount = qrm->value(0).toInt() + 1;

    //qrm->exec( "select sum(price * qty) from tmp_recipe");
    qrm->exec( "select sum(amount) from tmp_recipe");
    qrm->next();
    ui->leAmount->setText(qrm->value(0).toString());

    if(qFuzzyCompare( qrm->value(0).toDouble() , 0))
    {
        ui->pbSave->setEnabled(false);
    }else{
        ui->pbSave->setEnabled(true);
    }

}

void Form_ys_bzgl::process_combine_item()
{

    qDebug()<<"process_combine_item()处理组合项目\n";
    qrm->exec("select max(seq) from tmp_recipe");
    qrm->next();
    newRecipeRecItemCount = qrm->value(0).toInt() + 1;

    sq = "select * from tmp_recipe where ext_code = '1'";
    qrm->exec(sq);

    if(!qrm->next())
    {
        //临时表中无组合项目，直接返回
        qDebug()<<"处方临时表中没有组合项目。\n";
        return;
    }

    QString item_code, item_name, item_type, qty;

    while(true)
    {
        item_code = qrm->value("item_code").toString();
        item_name = qrm->value("item_name").toString();
        item_type = qrm->value("item_type").toString();
        qty = qrm->value("qty").toString();

        qDebug()<<"item_type is : "<<item_type<<"\n";

        if(item_type == "3")
        {
            //治疗、检验、处置
            sq = "delete from tmp_group_content";
            qrmt->exec(sq);

            sq = " select (select count(*) from fin_com_undrugztinfo zt "
                 "       where zt.his_code = un.item_code"
                 "             and zt.package_code =  '%1') qty ,"//count(*) qty,
                 " unit_price, item_name, item_code, stock_unit, exedept_code,"
                 " unit_price, specs, fee_code, sys_class, valid_state "
                 " from fin_com_undruginfo un "
                 " where item_code in "
                 " (select distinct his_code "
                 "       from fin_com_undrugztinfo where package_code = '%1') "
                 " and un.special_flag = '1' ";  //可收费项目

            sq = sq.arg(item_code);
            qDebug()<<"提取组合项目内容："<<sq<<"\n";
            qro->exec(sq);

            int seq = 0;

            while(qro->next())
            {
                if(qro->value("valid_state").toString() != "1")
                {
                    QMessageBox::warning(this, "注意", "组合项目中的 "
                                         + qro->value("item_name").toString() + " 已停用！");

                    //qrm->exec("delete from tmp_recipe where item_code = '" + item_code + "'");

                    sq = "delete from tmp_recipe where ext_code = '1'";
                    qrm->exec(sq);

                    return;
                }

                seq ++ ;
                sq = "insert into tmp_group_content "
                     "("
                     "package_name, "
                     "package_code, "
                     "item_name, "
                     "item_code, "
                     "frequency, "
                     "usages,"
                     "usage_code, "
                     "once_dose , "
                     "dose_unit,"
                     "qty, "
                     "qty_unit,"
                     "seq,"
                     "item_type,"
                     "exe_deptcode,"
                     "ext_code,"
                     "price,"
                     "specs,"
                     "drug_quality,"
                     "DOSE_MODEL_CODE,"
                     "SELF_made,"
                     "FEE_CODE,"
                     "CLASS_CODE,"
                     "BASE_DOSE,"
                     "pack_qty,"
                     "center_grade,"
                        "center_code"
                     ")";
                sq += " values( '";
                sq += item_name + "','";
                sq += item_code + "','";
                sq += qro->value("item_name").toString() + "','";
                sq += qro->value("item_code").toString() + "','";
                sq += "','";//pub::getDicN("频次", qro->value("frequency_code").toString()) +
                sq += "','";//pub::getDicN("给药途径", qro->value("usage_code").toString()) +
                sq += "',";//qro->value("usage_code").toString() +
                sq += "0,'";//QString::number(qro->value("once_dose").toDouble()) +
                sq += "',";//qro->value("dose_unit").toString() +
                //sq += "1,'";//QString::number(qro->value("qty").toInt())
                sq += qro->value("qty").toString() + ",'";//QString::number(qro->value("qty").toInt())
                sq += qro->value("stock_unit").toString() + "', ";
                sq += QString::number(seq) +",'"; //qro->value("seqid").toString()
                sq += item_type + "','";//qro->value("item_type").toString() +
                sq += qro->value("exedept_code").toString() + "','";
                sq += "0',";//qro->value("ext_code").toString() +
                sq += qro->value("unit_price").toString() + ",'";
                sq += qro->value("specs").toString() + "','";
                sq += "','";//drug_quality
                sq += "','";//dose_model_code
                sq += "','";//self_made
                sq += qro->value("fee_code").toString() + "','";
                sq += qro->value("sys_class").toString() + "',"; //qro->value("class_code").toString()
                sq += "0,";//base_dose
                sq += "1,";//pack_qty

                qrot->exec("select center_item_grade, med_list_codg from fin_com_compare "
                           " where fixmedins_hilist_id = '" + qro->value("item_code").toString() + "'");

                qDebug()<<"查询项目医保等级："<<qrot->lastQuery()<<"\n";

                if(qrot->next())
                {
                    if(qrot->value(0).toString().isEmpty())
                    {
                        QString tip = "查询不到 fin_com_compare 中\"" ;
                        tip += qro->value("item_name").toString();
                        tip += "\"的医保等级！";
                        qDebug()<<tip<<"\n";
                        sq += "0,''";
                    }
                    else
                    {
                        sq += qrot->value(0).toString();
                        sq += ",'" + qrot->value(1).toString() + "'";
                    }
                }
                else
                {
                    sq += "0,''";
                }

                sq += ")";

                qDebug()<<"插入 tmp_group_content ： "<<sq<<"\n";

                if(!qrmt->exec(sq))
                {
                    QMessageBox::information(this, "注意", "插入 tmp_group_content 发生错误 \n" + qrm->lastError().text());
                    qDebug()<<qrm->lastError().text()<<"\n";
                    return;
                }


                sq = "replace into tmp_recipe ("
                     "specs, item_name, item_code, frequency, "
                     "freq_days, usages, usage_code, "
                     "once_dose, dose_unit,qty, "
                     "qty_unit,seq,item_type,ext_code ,exe_deptcode,"
                     "diag1,diag1c,diag2,diag2c,diag3,diag3c,price,"
                     "DOSE_MODEL_CODE,SELF_made,FEE_CODE,CLASS_CODE,BASE_DOSE,pack_qty,drug_quality,"
                     "amount, center_grade, center_code, package_name, package_code)"
                     " select "
                     " specs, item_name, item_code, frequency, get_freq_days(frequency), "
                     " usages, usage_code, once_dose , "
                     " dose_unit,qty * "
                        + qty + ", qty_unit,seq + "
                        + QString::number(newRecipeRecItemCount)
                        +" ,item_type,ext_code ,exe_deptcode,";
                sq += "'" + qrm->value("diag1").toString() + "','" + qrm->value("diag1c").toString() + "',";
                sq += "'" + qrm->value("diag2").toString() + "','" + qrm->value("diag1c").toString() + "',";
                sq += "'" + qrm->value("diag3").toString() + "','" + qrm->value("diag1c").toString() + "',";
                sq += " price, DOSE_MODEL_CODE, SELF_made, FEE_CODE, CLASS_CODE, BASE_DOSE, pack_qty, drug_quality, ";
                sq += "qty * " + qty + " * price, center_grade, center_code, package_name, package_code";
                sq +=" from tmp_group_content t ";

                qrmt->exec(sq);
                qDebug()<<"组套数据插入临时处方表："<<sq<<"\n";

            }


        }

        if(!qrm->next())
        {
            break;
        }

    }

    sq = "delete from tmp_recipe where ext_code = '1'";
    qrm->exec(sq);

    qDebug()<<"process_combine_item()处理组合项目结束\n";
}

void Form_ys_bzgl::on_pbRemoveItem_clicked()
{
    if(!ui->tvRecipeNew->currentIndex().isValid()){
        QMessageBox::information(this, "注意", "请指定需要删除的数据行！");
        return;
    }
    QString itName = ui->tvRecipeNew->currentIndex().siblingAtColumn(0).data().toString();
    sq = "delete from tmp_recipe where item_name = '" + itName +"'" ;

    qrm->exec(sq);

    tvRecipeNewRefresh(0);
}

void Form_ys_bzgl::on_pbAddItem_clicked()
{
    //

    if(!statusCheck("item"))
    {
        return;
    }

    getDiags(); // 读取当前项目关联的诊断

    newRecipeRecItemCount ++ ;//处方序号
    sq = "select item_name from tmp_recipe where item_code = '"+cur_item_code+"'";
    qDebug()<<sq;
    qrm->exec(sq);
    QString itmtp;
    if(ui->cbbRange->currentText() == "西药中成药")
    {
        itmtp = "1";
    }
    else if(ui->cbbRange->currentText() == "耗材")
    {
        itmtp = "2";
    }
    else if(ui->cbbRange->currentText() == "诊疗")
    {
        itmtp = "3";
    }
    else if(ui->cbbRange->currentText() == "中草药")
    {
        itmtp = "4";
    }
    else
    {
        QMessageBox::information(this, "注意", "项目范围错误！");
        return;
    }

    QString oper_dept_code; //执行科室
    qrmt->exec("select dept_code from com_department "
              " where dept_name = '"+ui->cbbExecDept->currentText()+"'");
    if(!qrmt->next())
    {
        QMessageBox::information(this, "注意", "保存错误，执行科室不可以为空！");
        return;
    }
    oper_dept_code = qrmt->value(0).toString();

    if((itmtp == "1" || itmtp == "4") && !ui->ckb_ignore_store_sum->isChecked())
    {
        //西药、中成药、中草药，检查库存是否有效
        sq = "select store_sum from pha_com_stockinfo where ";
        sq += " drug_code ='" + cur_item_code + "' ";
        sq += " and drug_dept_code = '" + oper_dept_code + "'";
        qDebug()<<"西药、中成药、中草药，检查库存是否有效 : "<<sq;
        qrot->exec(sq);

        if(!qrot->next() || qrot->value(0).toInt() < 1)
        {
            QMessageBox::information(this, "注意", "指定的执行药房无有效数量！");
            return;
        }
    }

    if(qrm->next())
    {
        //项目已经存在，做变更

        sq = "update tmp_recipe set qty = " + QString::number(ui->spCnt->value()) + ", ";//
        sq += "amount = price * " + QString::number(ui->spCnt->value()) + ", ";//
        sq += "frequency = '" + ui->cbbFreq->currentText() + "', ";
        sq += "freq_days = get_freq_days(frequency),";

        if(itmtp == "1"){
            //药品相关属性
            sq += "usages = '" + ui->cbbUsage->currentText() + "', ";
            sq += "usage_code = '" + pub::getDicC("给药途径",ui->cbbUsage->currentText()) + "',";
            sq += "once_dose = " + ui->leUseCnt->text() + ", ";
            //sq += "dose_unit = '" + ui->cbbDoseUnit->currentText() + "', ";
            sq += "dose_unit = '" + ui->le_dose_unit->text() + "', ";
        }
        sq += "qty_unit = '" + ui->cbbPackUnit->currentText() + "', ";
        sq += "item_type = '" + itmtp + "', ";
        sq += "exe_deptcode = '" + oper_dept_code + "', ";  //执行科室
        sq += "diag1 = '" + diags[0] + "', ";
        sq += "diag1c = '" + diags[1] + "',";
        sq += "diag2 = '" + diags[2] + "', ";
        sq += "diag2c = '" + diags[3] + "',";
        sq += "diag3 = '" + diags[4] + "', ";
        sq += "diag3c = '" + diags[5] + "'";
        sq += " where item_name = '"+ui->leItemName->text()+"'";
        if(!qrm->exec(sq))
        {
            QMessageBox::information(this, "注意", "处方项目变更失败！\n " + qrm->lastError().text());
            qDebug()<<"处方项目变更失败 "<<qrm->lastError().text();
            qDebug()<<sq;
            return;
        }
        tvRecipeNewRefresh(0);
        return;
    }

    sq = "insert into tmp_recipe (package_name, package_code, item_name, item_code, frequency, "
         "freq_days, usages, usage_code, once_dose, dose_unit, "
         " qty, qty_unit,seq,item_type,ext_code ,exe_deptcode,"
         "diag1,diag1c,diag2,diag2c,diag3,diag3c,price,specs,"
         "DOSE_MODEL_CODE,SELF_made,FEE_CODE,CLASS_CODE,BASE_DOSE, "
         "pack_qty, drug_quality,center_grade,center_code,amount"
         ")";
    sq += " values('";
    sq += ui->leItemName->text() + "','";//直接录入，package = item
    sq += mpRecipeItemInfo["item_code"] + "','";
    sq += ui->leItemName->text() + "','";
    sq += mpRecipeItemInfo["item_code"] + "','";
    sq += ui->cbbFreq->currentText() + "',";
    sq += " get_freq_days('" + ui->cbbFreq->currentText() + "'),'";
    sq += ui->cbbUsage->currentText() + "','";
    sq += pub::getDicC("给药途径",ui->cbbUsage->currentText()) + "',";
    sq += (ui->leUseCnt->text().isEmpty() ? "0" : ui->leUseCnt->text()) + ",'";
    //sq += ui->cbbDoseUnit->currentText() + "',";
    sq += ui->le_dose_unit->text() + "',";
    sq += QString::number(ui->spCnt->value()) + ",'";  //
    sq += ui->cbbPackUnit->currentText() + "',";
    sq += QString::number( newRecipeRecItemCount ) +",'";
    sq += itmtp +"','" + mpRecipeItemInfo["ext_code"] +"','"+ oper_dept_code + "',"; //执行科室
    sq += "'" + diags[0] + "','" + diags[1] + "',";
    sq += "'" + diags[2] + "','" + diags[3] + "',";
    sq += "'" + diags[4] + "','" + diags[5] + "',";
    sq += mpRecipeItemInfo["price"] + ",'" + mpRecipeItemInfo["specs"] + "','";
    sq += mpRecipeItemInfo["DOSE_MODEL_CODE"] + "','" + mpRecipeItemInfo["SELF_MADE"] + "','";
    sq += mpRecipeItemInfo["FEE_CODE"] + "','" + mpRecipeItemInfo["CLASS_CODE"] + "','";
    sq += mpRecipeItemInfo["BASE_DOSE"] + "',";
    sq += mpRecipeItemInfo["pack_qty"] + ",'";
    sq += mpRecipeItemInfo["drug_quality"] +"',";
    sq += mpRecipeItemInfo["center_grade"] +",";
    sq += "'" + mpRecipeItemInfo["center_code"] +"',";
    sq += QString::number(mpRecipeItemInfo["price"].toDouble() * ui->spCnt->value()) ;

    sq += ")" ;//mpRecipeItemInfo["amount"]

    qDebug()<<"save temporary recipe item : "<<sq;
    if(!qrm->exec(sq)){
        QMessageBox::information(this, "注意", "保存错误，请确认数据项目完整且有效！");
        qDebug()<<"sql is : "<<sq;
        return;
    }

    tvRecipeNewRefresh(0);
}

void Form_ys_bzgl::getDiags()
{
    diags.clear();
    if(ui->ckbDiag1->isChecked() && !ui->le_diag1->text().isEmpty())
    {
        //diags << ui->cbbDiag1->currentText().trimmed() ;
        diags << ui->le_diag1->text();
        diags << getNatCode(ui->cbbDiag1->currentText().trimmed(), "2");
    }
    if(ui->ckbDiag2->isChecked() && !ui->le_diag2->text().isEmpty())
    {
        //diags << ui->cbbDiag2->currentText().trimmed() ;
        diags << ui->le_diag2->text();
        diags << getNatCode(ui->cbbDiag2->currentText().trimmed(), "2");
    }
    if(ui->ckbDiag3->isChecked() && !ui->le_diag3->text().isEmpty())
    {
        //diags << ui->cbbDiag3->currentText().trimmed() ;
        diags << ui->le_diag3->text();
        diags << getNatCode(ui->cbbDiag3->currentText().trimmed(), "2");
    }
    for(int i = diags.size(); i< 6; i++)
    {
        diags << "";
    }
    qDebug()<<"diags : " << diags;
}

void Form_ys_bzgl::on_leSearchG_returnPressed()
{
    //直接录入处方
    //if(!statusCheck(1)) return;
    mpRecipeItemInfo.clear();

    if(ui->cbbRange->currentText() == "西药中成药"
            || ui->cbbRange->currentText() == "中草药")
    {
        QString drug_type;

        if(ui->cbbRange->currentText() == "西药中成药")
        {
            drug_type = "'P','Z'";
        }
        else
        {
            drug_type = "'C'";
        }

        QString key = ui->leSearchG->text().trimmed();

        sq = "select BASE.trade_name 药品名称, BASE.specs 规格, BASE.drug_code, "
             "BASE.pack_qty, BASE.drug_type,BASE.retail_price, "
             " BASE.pack_unit, BASE.drug_quality , "
             "BASE.DOSE_MODEL_CODE,BASE.SELF_Flag,BASE.FEE_CODE,"
             "BASE.CLASS_CODE,BASE.BASE_DOSE,"
             " STO.store_sum / STO.pack_qty 库存数量, "
             " COMP.FAC_NAME 生产厂家, base.dose_unit,'0'" // last 0 is fill item
             " from pha_com_baseinfo base"
             " LEFT JOIN PHA_COM_COMPANY comp on COMP.FAC_CODE = BASE.PRODUCER_CODE"
             " left join PHA_COM_STOCKINFO sto on sto.drug_code = base.drug_code "
             " where BASE.valid_state = '1' "
             " and ( BASE.spell_code like '%%1%'"
             " or BASE.trade_name like '%%2%')"
             " and base.drug_type in(" + drug_type + ")";

        if(!ui->ckb_ignore_store_sum->isChecked())
        {
            sq += " and sto.store_sum > 0 and STO.drug_dept_code = "
                  " (select dept_code from pha_sto_setdept dept "
                  " where dept.room_code = '" ;
            sq += pub::dp_code + "' and DEPT.drug_type = BASE.DRUG_TYPE )";
        }

        sq = sq.arg(key.toUpper()).arg(key);

    }
    else if(ui->cbbRange->currentText() == "耗材")
    {
        sq = "select item_name, 'specs', item_code, 1, "//0-3
             "exedept_code, unit_price,stock_unit pack_unit,'-','-','-',"//4-9
             "FEE_CODE,sys_class,1 ,'-','-','-','',unitflag "//10-17
             " from fin_com_undruginfo where valid_state = '1' and "
             " fee_code = '010' and ( spell_code like ";
        sq += "'%"+ui->leSearchG->text().trimmed().toUpper();
        sq += "%' or item_name like '%"+ui->leSearchG->text().trimmed()+"%')";
    }
    else if(ui->cbbRange->currentText() == "诊疗")
    {
        sq = "select item_name, 'specs', item_code, 1, "//0-3
             "exedept_code, unit_price,stock_unit pack_unit,'-','-','-',"//4-9
             "FEE_CODE,sys_class,1 ,'-','-','-','',unitflag "//10-17
             " from fin_com_undruginfo where valid_state = '1' and "
             " fee_code <> '010' and ( spell_code like ";
        sq += "'%"+ui->leSearchG->text().trimmed().toUpper();
        sq += "%' or item_name like '%"+ui->leSearchG->text().trimmed()+"%')";
    }
    else
    {
        QMessageBox::information(this, "注意", "范围选择无效！");
        return;
    }

    qDebug()<<"on_leSearchG_returnPressed select sql : "<<sq;

    mdSearchPop->setQuery( sq , pub::db_o);

    if(mdSearchPop->rowCount() == 0)
    {
        QMessageBox::information(this, "注意", "指定关键字找不到有效的项目！");
        return;
    }
    else if(mdSearchPop->rowCount() == 1)
    {
        mpRecipeItemInfo["specs"] = mdSearchPop->record(0).value(1).toString();
        mpRecipeItemInfo["pack_qty"] = mdSearchPop->record(0).value(3).toString();
        mpRecipeItemInfo["item_code"] = mdSearchPop->record(0).value(2).toString();

        //if item is drug, current value is "drug_type", else is "exec_dept"
        mpRecipeItemInfo["exec_dept"] = mdSearchPop->record(0).value(4).toString();

        mpRecipeItemInfo["pack_unit"] = mdSearchPop->record(0).value(6).toString();
        mpRecipeItemInfo["price"] = mdSearchPop->record(0).value(5).toString();
        mpRecipeItemInfo["drug_quality"] = mdSearchPop->record(0).value(7).toString().trimmed();

        mpRecipeItemInfo["DOSE_MODEL_CODE"] = mdSearchPop->record(0).value(8).toString();
        mpRecipeItemInfo["SELF_MADE"] = mdSearchPop->record(0).value(9).toString();
        mpRecipeItemInfo["FEE_CODE"] = mdSearchPop->record(0).value(10).toString();
        mpRecipeItemInfo["CLASS_CODE"] = mdSearchPop->record(0).value(11).toString();
        mpRecipeItemInfo["BASE_DOSE"] = mdSearchPop->record(0).value(12).toString().trimmed();
        mpRecipeItemInfo["DOSE_UNIT"] = mdSearchPop->record(0).value(15).toString().trimmed();
        ui->leItemName->setText(mdSearchPop->record(0).value(0).toString());
        ui->leSpecs->setText( mdSearchPop->record(0).value(1).toString());
        ui->le_dose_unit->setText( mdSearchPop->record(0).value(15).toString());

        mpRecipeItemInfo["ext_code"] = mdSearchPop->record(0).value(17).toString();
    }
    else
    {
        dlgGetItem->setDisplay(*mdSearchPop,QRect(300, 150, 800, 500),"","0.3^0.2^0^0^0^0^0^0^0^0^0^0^0^0.1^0.3^0^0^0");

        dlgGetItem->setModal(true);
        dlgGetItem->exec();

        QString popRetStr = dlgGetItem->retStr();
        if(popRetStr.isEmpty())
        {
            return;
        }
        qDebug()<<"pop select return value is : "<<popRetStr;

        mpRecipeItemInfo["specs"] = pub::getStr(popRetStr, "^", 2);
        mpRecipeItemInfo["item_code"] = pub::getStr(popRetStr, "^", 3);
        mpRecipeItemInfo["pack_qty"] = pub::getStr(popRetStr, "^", 4);
        ui->leItemName->setText(pub::getStr(popRetStr, "^", 1));
        ui->leSpecs->setText( pub::getStr(popRetStr, "^", 2));
        ui->le_dose_unit->setText( pub::getStr(popRetStr, "^", 16));

        //if item is drug, current value is "drug_type", else is "exec_dept"
        mpRecipeItemInfo["exec_dept"] = pub::getStr(popRetStr, "^", 5);
        mpRecipeItemInfo["pack_unit"] = pub::getStr(popRetStr, "^", 7);
        mpRecipeItemInfo["price"] = pub::getStr(popRetStr, "^", 6);
        mpRecipeItemInfo["drug_quality"] = pub::getStr(popRetStr, "^", 8).trimmed();
        mpRecipeItemInfo["DOSE_MODEL_CODE"] = pub::getStr(popRetStr, "^", 9).trimmed();
        mpRecipeItemInfo["SELF_MADE"] = pub::getStr(popRetStr, "^", 10).trimmed();
        mpRecipeItemInfo["FEE_CODE"] = pub::getStr(popRetStr, "^", 11).trimmed();
        mpRecipeItemInfo["CLASS_CODE"] = pub::getStr(popRetStr, "^", 12).trimmed();
        mpRecipeItemInfo["BASE_DOSE"] = pub::getStr(popRetStr, "^", 13).trimmed();
        mpRecipeItemInfo["DOSE_UNIT"] = pub::getStr(popRetStr, "^", 16).trimmed();

        mpRecipeItemInfo["ext_code"] = mdSearchPop->record(0).value(17).toString();
    }

    if(ui->cbbRange->currentText() == "西药中成药")
    {
        //value name "exec_dept" actually is "drug_type"
        sq = "select a.dept_code,b.dept_name from pha_sto_setdept a,"
             " com_department b where a.room_code = '"+pub::dp_code;
        sq += "' and a.drug_type = '"+mpRecipeItemInfo["exec_dept"]+"' and a.dept_code = b.dept_code";
        qrmt->exec(sq);
        qrmt->next();
        mpRecipeItemInfo["exec_dept"] = qrmt->value(1).toString();
    }else{
        sq = "select dept_name from com_department where dept_code = '"+mpRecipeItemInfo["exec_dept"]+"'";
        qrmt->exec(sq);
        qrmt->next();
        mpRecipeItemInfo["exec_dept"] = qrmt->value(0).toString();
    }

    ui->cbbExecDept->setCurrentText(mpRecipeItemInfo["exec_dept"]);
    ui->cbbPackUnit->setCurrentText(mpRecipeItemInfo["pack_unit"]);
    cur_item_code = mpRecipeItemInfo["item_code"];

    sq = "select center_item_grade, med_list_codg from fin_com_compare "
         " where fixmedins_hilist_id = '" + cur_item_code + "'";
    qDebug()<<" get center grade : "<< sq;
    qro->exec(sq);

    if(qro->next())
    {

        if(qro->value(0).toString().isEmpty())
        {
            QString tip = "查询不到 fin_com_compare 中\"" ;
            tip += ui->leItemName->text();
            tip += "\"的医保等级！";
            //QMessageBox::information(this, "注意", tip);
            qDebug()<<tip;
            mpRecipeItemInfo["center_grade"] = "0";
            mpRecipeItemInfo["center_code"] = "";
        }
        else
        {
            mpRecipeItemInfo["center_grade"] = qro->value(0).toString();
            mpRecipeItemInfo["center_code"] = qro->value(1).toString();
        }

    }else
    {
        mpRecipeItemInfo["center_grade"] = "0";
        mpRecipeItemInfo["center_code"] = "";
    }

    ui->spCnt->setFocus();

}

void Form_ys_bzgl::on_pbSearch_clicked()
{
    on_leSearchG_returnPressed();
}

void Form_ys_bzgl::on_tvRecipeNew_clicked(const QModelIndex &index)
{

    ui->leItemName->setText(index.siblingAtColumn(0).data().toString());
    ui->leSpecs->setText(index.siblingAtColumn(10).data().toString());
    ui->spCnt->setValue(index.siblingAtColumn(2).data().toInt());
    ui->leUseCnt->setText(index.siblingAtColumn(11).data().toString());
    ui->cbbPackUnit->setCurrentText(index.siblingAtColumn(3).data().toString());
    ui->cbbUsage->setCurrentText(index.siblingAtColumn(6).data().toString());
    ui->cbbFreq->setCurrentText(index.siblingAtColumn(7).data().toString());
    ui->le_dose_unit->setText(index.siblingAtColumn(12).data().toString());
    ui->cbbRange->setCurrentText(index.siblingAtColumn(15).data().toString());

    qrmt->exec("select dept_name from com_department where dept_code = '"
               + index.siblingAtColumn(14).data().toString() + "'");
    qrmt->next();

    QString dpnm = qrmt->value(0).toString();

    if(ui->cbbExecDept->findText(dpnm) < 0)
    {
        ui->cbbExecDept->setCurrentIndex(-1);
    }else{
        ui->cbbExecDept->setCurrentText(dpnm);
    }

    cur_item_code = index.siblingAtColumn(13).data().toString();

}

void Form_ys_bzgl::on_tvRecipeNew_doubleClicked(const QModelIndex &index)
{
    if(index.siblingAtColumn(14).data().toString() == "西药中成药")
    {
        QString item_code = index.siblingAtColumn(12).data().toString();
        //显示更多信息。待完成。
    }

    //cur_item_code = index.siblingAtColumn(12).data().toString();
    //on_tvRecipeNew_clicked(index);
}

void Form_ys_bzgl::on_pbRecipeClear_clicked()
{
    tvRecipeNewRefresh(1);
}

void Form_ys_bzgl::threadMsg(QString s)
{
    if(s == "finish"){
        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();
    }
    else if(s.left(3) == "msg")
    {
        dlgDelay->setText(sqlMsg[pub::getStr(s, "^", 2).toInt()]);
    }
    else if(s.left(8) == "rollback")
    {
        dlgDelay->setText("线程 SQL 发生错误，正在回滚。。。");
    }
    else if(s.left(3) == "err"){
        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();
        qDebug()<<" SQL thread " +s;
        QMessageBox::warning(this, "注意", "线程中的sql执行发生错误！\n" + s);
    }
    else
    {
        qDebug()<<" SQL thread return invalid message : " +s;
    }
}

QString Form_ys_bzgl::getDictValue(QString dic_type, QString search_value)
{
    //根据字典类别，字典值或字典代码进行检索
    QString s = "select code,name,dept_code from com_dict_com where dic_type = '" + dic_type + "'";
    s += " and (code = '" + search_value + "' or name = '" + search_value + "')";
    qrmt->exec(s);
    if(qrmt->next())
    {
        return qrmt->value(0).toString() + "^" + qrmt->value(1).toString() + "^" + qrmt->value(2).toString()  ;
    }
    else
    {
        return "";
    }
}

QString Form_ys_bzgl::getDeptName(QString dept_code)
{
    //由科室代码检索科室名称
    qrmt->exec("select dept_name from com_department where dept_code = '"+dept_code+"'");
    if(qrmt->next())
    {
        return qrmt->value(0).toString();
    }
    else{
        return "";
    }
}

void Form_ys_bzgl::on_pbRemoveUncharge_clicked()
{
    if(!ui->tvRecipe->currentIndex().isValid())
    {
        QMessageBox::information(this, "注意", "未选定有效数据行！");
        return;
    }
    QString itemseq = ui->tvRecipe->currentIndex().siblingAtColumn(9).data().toString();

    QMessageBox::StandardButton result;
    result = QMessageBox::warning(NULL, "注意", "确定要撤销未结算处方项目？",QMessageBox::Yes|QMessageBox::No);
    if(result == QMessageBox::No){
        return;
    }

    //撤销诊间支付消息
    if(mpPatientInfo["pact_code"] == "2")
    {
        //医保患者
        save_5465("0");
    }


    //收费明细设置无效标志
    //fin_opb_feedetail.mo_order = met_order_recipedetail.sequence_no
    sq = "update fin_opb_feedetail set cancel_flag = '0' where "
         " mo_order = '" + itemseq + "' and cancel_flag = '1' and pay_flag = '0'" ;
    qro->exec(sq);
    if(qro->numRowsAffected() < 1)
    {
        QMessageBox::information(this, "注意", "数据已经收费无法撤销！");
        return;
    }

    //诊间处方表设置删除标志
    sq = "update met_ord_recipedetail set status = '4' "
         " where charge_flag = '0' and sequence_no = '" + itemseq + "'";
    qro->exec(sq);

    save_medical_plan();

    save_senior_recipe_no();

    fresh_e_rec_zd();

    getRegDateRecipe();

    ui->pbRemoveUncharge->setEnabled(false);
}


void Form_ys_bzgl::on_tvRecipe_clicked(const QModelIndex &index)
{

    if(index.siblingAtColumn(8).data().toString() == "0")
    {
        ui->pbRemoveUncharge->setEnabled(true);
    }
    else
    {
        ui->pbRemoveUncharge->setEnabled(false);
    }

    //计算历史开药数据
    qDebug()<<"计算历史开药数据\n";
    sq = " select fee.days, fee.oper_date "
         " from fin_opb_feedetail fee "
         " where fee.card_no = '%1'"
         " and fee.item_code = '%2'"
         " and fee.cancel_flag = '1' and fee.oper_date > to_date('%3','yyyy-mm-dd') - 90 "
         " and trunc(fee.oper_date) <= to_date('%3','yyyy-mm-dd')";

    //处方项目关联的挂号记录状态应为有效
    sq += " and (select reg.valid_flag from fin_opr_register reg"
          "      where reg.clinic_code = fee.clinic_code"
          "      and rownum = 1 ) = '1' ";

    sq += " order by fee.oper_date desc ";

    sq = sq.arg(mpPatientInfo["card_no"])
            .arg(index.siblingAtColumn(13).data().toString())
            .arg(index.siblingAtColumn(14).data().toDate().toString("yyyy-MM-dd"));
    qro->exec(sq);
    qDebug()<<"检索90天累计用量："<<sq<<"\n";

    int count = 0;
    int maxCount = 0;  //最大可用处方天数
    int realDays = 0;   //处方日期至当前日期的天数
    QDate curD, RecipeD,maxD;

    curD = index.siblingAtColumn(14).data().toDate();
    while(qro->next())
    {
        RecipeD = qro->value(1).toDate();
        count += qro->value(0).toInt();
        realDays = RecipeD.daysTo(curD);

        if(count - realDays > maxCount)
        {
            //保存最大可用处方天数的处方日期
            maxCount = count - realDays;
            maxD = RecipeD;
        }
    }

    ui->le_left_days->setText(QString::number(maxCount));

}

void Form_ys_bzgl::on_tvRecipe_doubleClicked(const QModelIndex &index)
{
    on_tvRecipe_clicked(index);
}

void Form_ys_bzgl::tmDiagTimerStarter()
{
    //if(ui->ta b_5->isHidden())
    //{
    //    return;
    //}
    if(tmDiag->isActive())
    {
        tmDiag->stop();
    }
    //if(!strDiag.isEmpty())
    {
        tmDiag->start(500);
    }

}

void Form_ys_bzgl::tmDiagTimeout()
{
    tmDiag->stop();

    sq = "select item_name from com_dict_icpc where ";
    sq += " instr(dept_code, '" + pub::dp_code + "') > 0 and type = '2' " ;
    sq += " and (py like UPPER('%" + strDiag + "%') or item_name like '%" + strDiag + "%')";
    sq += " order by convert(item_name using gbk)";
    if(ui->cbbDiag1->hasFocus())
    {
        ui->cbbDiag1->blockSignals(true);
        if(ui->cbbDiag1->findText(strDiag) < 0) //列表内容 找不到 currentText
        {
            if(strDiag.isEmpty())
            {
                //current text 为空，整理下拉列表内容，置 current text 为空
                fillCombo(ui->cbbDiag1 , sq, -1);
            }
            else
            {
                //current text 不为空，整理下拉列表内容，置 current text 列表第一项
                fillCombo(ui->cbbDiag1 , sq, 0);
                on_cbbDiag1_currentTextChanged(ui->cbbDiag1->currentText());
            }
        }

        ui->cbbDiag1->blockSignals(false);
    }
    else if(ui->cbbDiag2->hasFocus())
    {
        ui->cbbDiag2->blockSignals(true);
        if(ui->cbbDiag2->findText(strDiag) < 0)
        {
            if(strDiag.isEmpty())
            {
                fillCombo(ui->cbbDiag2 , sq, -1);
            }
            else
            {
                fillCombo(ui->cbbDiag2 , sq, 0);
                on_cbbDiag2_currentTextChanged(ui->cbbDiag2->currentText());
            }
        }

        ui->cbbDiag2->blockSignals(false);
    }
    else if(ui->cbbDiag3->hasFocus())
    {
        ui->cbbDiag3->blockSignals(true);
        if(ui->cbbDiag3->findText(strDiag) < 0)
        {
            if(strDiag.isEmpty())
            {
                fillCombo(ui->cbbDiag3 , sq, -1);
            }
            else
            {
                fillCombo(ui->cbbDiag3 , sq, 0);
                on_cbbDiag3_currentTextChanged(ui->cbbDiag3->currentText());
            }
        }

        ui->cbbDiag3->blockSignals(false);
    }
}


void Form_ys_bzgl::tmTvWidthReset()
{
    tmTvWidth->stop();
}

void Form_ys_bzgl::on_leItemName_textChanged(const QString &arg1)
{
    if(!arg1.isEmpty())
    {
        ui->pbSave->setEnabled(false);
    }
}

void Form_ys_bzgl::on_pbGetLastInfo_clicked()
{

    sq = " select distinct rlts 关系, trustee_name 姓名 , trustee_tel, trustee_certno "
         " from ys_bz_e_rec "
         " where card_no = '%1' "
         " and trustee_name <> '' "
         " and trustee_name is not null "
         " order by atinc desc";
    sq = sq.arg(mpPatientInfo["card_no"]);

    qDebug()<<"提取代取药信息 : " << sq;
    mdSearchPop->setQuery( sq , pub::db_m);

    if(mdSearchPop->rowCount() < 1)
    {
        QMessageBox::information(this, "注意", "未找到有效代取药人信息！");
        return;
    }

    dlgGetItem->setDisplay(*mdSearchPop,QRect(500, 500, 500, 200),"","0.4^0.4^0^0^0");
    dlgGetItem->setModal(true);
    dlgGetItem->exec();

    QString popRetStr = dlgGetItem->retStr();
    if(popRetStr.isEmpty())
    {
        return;
    }
    qDebug()<<"pop select return value is : "<<popRetStr;

    ui->leTrustee->setText(pub::getStr(popRetStr, "^", 2));
    ui->leTrusteeI->setText(pub::getStr(popRetStr, "^", 4));
    ui->leTrusteeP->setText(pub::getStr(popRetStr, "^", 3));
    ui->cbbTrusteeRlt->setCurrentText(pub::getStr(popRetStr, "^", 1));

}

void Form_ys_bzgl::on_pbEditAgain_clicked()
{
    QMessageBox::StandardButton result;
    result = QMessageBox::warning(NULL, "注意", "确定要重新编辑全部未结算处方项目？",QMessageBox::Yes|QMessageBox::No);
    if(result == QMessageBox::No)
    {
        return;
    }

    //撤销诊间支付消息
    if(mpPatientInfo["pact_code"] == "2")
    {
        //医保患者
        save_5465("0");
    }

    sq = "select m.item_name, m.item_code, m.frequency_name, m.usage_name, m.usage_code, m.once_dose, "
         "m.once_unit, m.qty, m.item_unit,m.SEQUENCE_NO,m.DRUG_FLAG,m.EXEC_DPCD ,m.CLINICDIAG_NAME,"
         "m.CLINICDIAG_CODE,m.CLINICOTHERDIAG1_NAME,m.CLINICOTHERDIAG1_CODE,m.cLINICOTHERDIAG2_NAME,"
         "m.CLINICOTHERDIAG2_CODE,m.unit_price,m.specs,m.DOSE_MODEL_CODE,m.SELF_made,m.FEE_CODE,"
         "m.CLASS_CODE,m.BASE_DOSE, m.pack_qty, m.drug_quanlity,"
         " f.center_item_grade,f.center_code,m.OWN_COST,m.see_no,m.days, fee.package_name, fee.package_code"
         " from MET_ORD_RECIPEDETAIL m "
         " left JOIN FIN_COM_COMPARE f on f.fixmedins_hilist_id = m.ITEM_CODE "
         " left join fin_opb_feedetail fee on fee.mo_order = m.sequence_no "
         " where m.clinic_code = '" + mpPatientInfo["clinic_code"] ;
    sq += "' and m.charge_flag = '0' and m.status = '0' " ;
    qDebug()<<"提取未结算处方项目："<<sq;
    qrot->exec(sq);
    qrot->next();
    if(qrot->isNull(0))
    {
        QMessageBox::warning(this, "注意", "找不到未结算处方项目!");
        return;
    }

    //清空临时处方表
    qrm->exec("delete from tmp_recipe");

    QString seqs = "0"; //用于在诊间处方表加注撤销标记
    QString see_nos = "'0'";

    while(true)
    {
        sq = "insert into tmp_recipe (package_code, package_name, "
             "item_name, item_code, frequency, freq_days, "
             "usages, usage_code, once_dose, dose_unit, "
             "qty, qty_unit,seq,item_type,ext_code ,exe_deptcode,"
             "diag1,diag1c,diag2,diag2c,diag3,diag3c,"
             "price,specs,DOSE_MODEL_CODE,SELF_made,"
             "FEE_CODE,CLASS_CODE,BASE_DOSE, "
             "pack_qty, drug_quality,center_grade,center_code,amount"
                 ") values (";
        sq += "'" + qrot->value("package_code").toString() + "',";
        sq += "'" + qrot->value("package_name").toString() + "',";
        sq += "'" + qrot->value("item_name").toString() + "',";
        sq += "'" + qrot->value("item_code").toString() + "',";
        sq += "'" + qrot->value("frequency_name").toString() + "',";
        sq += "get_freq_days('" + qrot->value("frequency_name").toString() + "'),";

        sq += "'" + qrot->value("usage_name").toString() + "',";
        sq += "'" + qrot->value("usage_code").toString() + "',";
        sq += qrot->value("once_dose").toString() + ",";
        sq += "'" + qrot->value("once_unit").toString() + "',";

        if(qrot->value("DRUG_FLAG").toString() == "4")
        {
            //草药
            sq += qrot->value("qty").toString() + "/" + qrot->value("days").toString() + ",";
        }
        else
        {
            sq += qrot->value("qty").toString() + ",";
        }


        sq += "'" + qrot->value("item_unit").toString() + "',";
        sq += qrot->value("SEQUENCE_NO").toString() + ",";
        sq += "'" + qrot->value("DRUG_FLAG").toString() + "',";
        sq += "'0',";//ext_code,组合项目标志
        sq += "'" + qrot->value("EXEC_DPCD").toString() + "',";

        sq += "'" + qrot->value("CLINICDIAG_NAME").toString() + "',";
        sq += "'" + qrot->value("CLINICDIAG_CODE").toString() + "',";
        sq += "'" + qrot->value("CLINICOTHERDIAG1_NAME").toString() + "',";
        sq += "'" + qrot->value("CLINICOTHERDIAG1_CODE").toString() + "',";
        sq += "'" + qrot->value("CLINICOTHERDIAG2_NAME").toString() + "',";
        sq += "'" + qrot->value("CLINICOTHERDIAG2_CODE").toString() + "',";

        sq += qrot->value("unit_price").toString() + ",";
        sq += "'" + qrot->value("specs").toString() + "',";
        sq += "'" + qrot->value("DOSE_MODEL_CODE").toString() + "',";
        sq += "'" + qrot->value("SELF_made").toString() + "',";

        sq += "'" + qrot->value("FEE_CODE").toString() + "',";
        sq += "'" + qrot->value("CLASS_CODE").toString() + "',";
        sq += "'" + qrot->value("BASE_DOSE").toString() + "',";

        sq += qrot->value("pack_qty").toString() + ",";
        sq += "'" + qrot->value("drug_quanlity").toString() + "',";
        sq += qrot->value("center_item_grade").toString() + ",";
        sq += "'" + qrot->value("center_code").toString() + "',";
        sq += qrot->value("OWN_COST").toString() ;

        sq += ")";

        qDebug()<<"插入数据至临时处方表："<<sq;
        if(!qrm->exec(sq))
        {
            QMessageBox::warning(this, "注意", qrot->value("item_name").toString()
                                 + " 在临时处方中重复出现，编辑时注意调整数量!");
            //return;
        }

        seqs += "," + qrot->value("SEQUENCE_NO").toString();
        see_nos += ",'" + qrot->value("see_no").toString() + "'";

        if(!qrot->next())
        {
            break;
        }
    }

    sq = "update met_ord_recipedetail set status = '4' where "
         " see_no in(" + see_nos + ") and sequence_no in (" + seqs + ")" ;
    qDebug()<<"撤销未付款诊间处方："<<sq;
    qrot->exec(sq);

    //fin_opb_feedetail.mo_order = met_order_recipedetail.sequence_no
    sq = "update fin_opb_feedetail set cancel_flag = '0' "
         " where mo_order in(" + seqs + ")";
    qDebug()<<"未付款收费明细设置作废："<<sq;
    qrot->exec(sq);

    save_medical_plan();

    save_senior_recipe_no();

    fresh_e_rec_zd();

    getRegDateRecipe();

    ui->tabWidget->setCurrentIndex(3);
    tvRecipeNewRefresh(0);

}

void Form_ys_bzgl::on_tvGroup_doubleClicked(const QModelIndex &index)
{
    on_tvGroup_clicked(index);
}

void Form_ys_bzgl::on_ckbDisplayCancel_clicked()
{
    getRegDateRecipe();
}

void Form_ys_bzgl::fresh_e_rec_zd()
{

    QString diags;   //当前存在的有效诊断

    sq = "select distinct CLINICDIAG_CODE,CLINICDIAG_NAME,CLINICOTHERDIAG1_CODE,CLINICOTHERDIAG1_NAME,"
         " CLINICOTHERDIAG2_CODE,CLINICOTHERDIAG2_NAME "
         " from met_ord_recipedetail "
         " where status <> '4' and clinic_code = '" + mpPatientInfo["clinic_code"] + "'";
    qDebug()<<"提取处方撤销之后，仍然存在的诊断:"<<sq;
    qro->exec(sq);

    while(qro->next())
    {
        diags += qro->value("CLINICDIAG_NAME").toString();
        diags += "^";
        diags += qro->value("CLINICOTHERDIAG1_NAME").toString();
        diags += "^";
        diags += qro->value("CLINICOTHERDIAG2_NAME").toString();
        diags += "^";
    }

    qDebug()<<"仍然存在的有效诊断 :"<<diags;

    //病志中保存的诊断
    sq = "select zd1, zd2, zd3, zd1c, zd2c, zd3c, "
         "zyzd1, zyzd2, zyzd3, zyzd1c, zyzd2c, zyzd3c,"
         "zyzh1, zyzh2, zyzh3, zyzh1c, zyzh2c, zyzh3c"
         " from ys_bz_e_rec "
         " where clinic_code = '" + mpPatientInfo["clinic_code"] + "'";
    qDebug()<<"提取当前病志中已经保存的诊断："<<sq;
    qrm->exec(sq);

    if(!qrm->next())
    {
        //尚未存储病志记录
        qDebug()<<"尚未存储病志记录";
        return;
    }

    QMap<QString, QString> old_diags;
    old_diags["zd1"] = qrm->value(0).toString();
    old_diags["zd2"] = qrm->value(1).toString();
    old_diags["zd3"] = qrm->value(2).toString();
    old_diags["zd1c"] = qrm->value(3).toString();
    old_diags["zd2c"] = qrm->value(4).toString();
    old_diags["zd3c"] = qrm->value(5).toString();
    old_diags["zyzd1"] = qrm->value(6).toString();
    old_diags["zyzd2"] = qrm->value(7).toString();
    old_diags["zyzd3"] = qrm->value(8).toString();
    old_diags["zyzd1c"] = qrm->value(9).toString();
    old_diags["zyzd2c"] = qrm->value(10).toString();
    old_diags["zyzd3c"] = qrm->value(11).toString();
    old_diags["zyzh1"] = qrm->value(12).toString();
    old_diags["zyzh2"] = qrm->value(13).toString();
    old_diags["zyzh3"] = qrm->value(14).toString();
    old_diags["zyzh1c"] = qrm->value(15).toString();
    old_diags["zyzh2c"] = qrm->value(16).toString();
    old_diags["zyzh3c"] = qrm->value(17).toString();

    if(diags.indexOf(old_diags["zd1"]) < 0)
    {
        //旧的诊断已经无效,后序依次前移
        old_diags["zd1"] = old_diags["zd2"];
        old_diags["zd1c"] = old_diags["zd2c"];
        old_diags["zyzd1"] = old_diags["zyzd2"];
        old_diags["zyzd1c"] = old_diags["zyzd2c"];
        old_diags["zyzh1"] = old_diags["zyzh2"];
        old_diags["zyzh1c"] = old_diags["zyzh2c"];

        old_diags["zd2"] = old_diags["zd3"];
        old_diags["zd2c"] = old_diags["zd3c"];
        old_diags["zyzd2"] = old_diags["zyzd3"];
        old_diags["zyzd2c"] = old_diags["zyzd3c"];
        old_diags["zyzh2"] = old_diags["zyzh3"];
        old_diags["zyzh2c"] = old_diags["zyzh3c"];

        old_diags["zd3"] = "";
        old_diags["zd3c"] = "";
        old_diags["zyzd3"] = "";
        old_diags["zyzd3c"] = "";
        old_diags["zyzh3"] = "";
        old_diags["zyzh3c"] = "";
    }

    if(!old_diags["zd2"].isEmpty() && diags.indexOf(old_diags["zd2"]) < 0)
    {
        //旧的诊断已经无效
        old_diags["zd2"] = old_diags["zd3"];
        old_diags["zd2c"] = old_diags["zd3c"];
        old_diags["zyzd2"] = old_diags["zyzd3"];
        old_diags["zyzd2c"] = old_diags["zyzd3c"];
        old_diags["zyzh2"] = old_diags["zyzh3"];
        old_diags["zyzh2c"] = old_diags["zyzh3c"];

        old_diags["zd3"] = "";
        old_diags["zd3c"] = "";
        old_diags["zyzd3"] = "";
        old_diags["zyzd3c"] = "";
        old_diags["zyzh3"] = "";
        old_diags["zyzh3c"] = "";
    }

    if(!old_diags["zd3"].isEmpty() && diags.indexOf(old_diags["zd3"]) < 0)
    {
        //旧的诊断已经无效
        old_diags["zd3"] = "";
        old_diags["zd3c"] = "";
        old_diags["zyzd3"] = "";
        old_diags["zyzd3c"] = "";
        old_diags["zyzh3"] = "";
        old_diags["zyzh3c"] = "";
    }

    //修改已经存在的记录。
    sq = " update ys_bz_e_rec e set ";
    sq += " zd1 = '" + old_diags["zd1"] + "',";
    sq += " zd2 = '" + old_diags["zd2"] + "',";
    sq += " zd3 = '" + old_diags["zd3"] + "',";
    sq += " zd1c = '" + old_diags["zd1c"] + "',";
    sq += " zd2c = '" + old_diags["zd2c"] + "',";
    sq += " zd3c = '" + old_diags["zd3c"] + "',";
    sq += " zyzd1 = '" + old_diags["zyzd1"] + "',";
    sq += " zyzd2 = '" + old_diags["zyzd2"] + "',";
    sq += " zyzd3 = '" + old_diags["zyzd3"] + "',";
    sq += " zyzd1c = '" + old_diags["zyzd1c"] + "',";
    sq += " zyzd2c = '" + old_diags["zyzd2c"] + "',";
    sq += " zyzd3c = '" + old_diags["zyzd3c"] + "',";
    sq += " zyzh1 = '" + old_diags["zyzh1"] + "',";
    sq += " zyzh2 = '" + old_diags["zyzh2"] + "',";
    sq += " zyzh3 = '" + old_diags["zyzh3"] + "',";
    sq += " zyzh1c = '" + old_diags["zyzh1c"] + "',";
    sq += " zyzh2c = '" + old_diags["zyzh2c"] + "',";
    sq += " zyzh3c = '" + old_diags["zyzh3c"] + "',";
    sq += " diag_date = curdate() ";
    sq += " where clinic_code = '" + mpPatientInfo["clinic_code"] + "'";
    qDebug()<<"保存有效的诊断"<<sq;
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "保存处方记录失败！\nerrmsg : "
                                 + qrm->lastError().text()+"\nsql : "+sq);
    }


}

void Form_ys_bzgl::on_rb_mode_med_clicked()
{
    if(ui->rb_mode_med->isChecked())
    {
        //西医
        qDebug()<<"curetnt mode is 西医";

        ui->lb_tr1->setHidden(true);
        ui->cbb_tr_diag1->setHidden(true);
        ui->cbb_tr_diag2->setHidden(true);
        ui->cbb_tr_diag3->setHidden(true);

        ui->lb_tr2->setHidden(true);
        ui->cbb_tr_symptom1->setHidden(true);
        ui->cbb_tr_symptom2->setHidden(true);
        ui->cbb_tr_symptom3->setHidden(true);

        ui->frm_bodychk_tr->setHidden(true);
        ui->frm_diag_basis->setHidden(true);
        ui->frm_similar_syndrom->setHidden(true);
        ui->frm_treatment_tr->setHidden(true);

    }
    else if(ui->rb_mode_tr_med->isChecked())
    {
        //中西医
        qDebug()<<"curetnt mode is 中西医";

        ui->lb_tr1->setHidden(false);
        ui->cbb_tr_diag1->setHidden(false);
        ui->cbb_tr_diag2->setHidden(false);
        ui->cbb_tr_diag3->setHidden(false);

        ui->lb_tr2->setHidden(false);
        ui->cbb_tr_symptom1->setHidden(false);
        ui->cbb_tr_symptom2->setHidden(false);
        ui->cbb_tr_symptom3->setHidden(false);

        ui->frm_bodychk_tr->setHidden(false);
        ui->frm_diag_basis->setHidden(false);
        ui->frm_similar_syndrom->setHidden(false);
        ui->frm_treatment_tr->setHidden(false);

    }
    else
    {
        //中医
        qDebug()<<"curetnt mode is 中医";

        ui->lb_tr1->setHidden(false);
        ui->cbb_tr_diag1->setHidden(false);
        ui->cbb_tr_diag2->setHidden(false);
        ui->cbb_tr_diag3->setHidden(false);

        ui->lb_tr2->setHidden(false);
        ui->cbb_tr_symptom1->setHidden(false);
        ui->cbb_tr_symptom2->setHidden(false);
        ui->cbb_tr_symptom3->setHidden(false);

        ui->frm_bodychk_tr->setHidden(false);
        ui->frm_diag_basis->setHidden(false);
        ui->frm_similar_syndrom->setHidden(false);
        ui->frm_treatment_tr->setHidden(false);
    }
}

void Form_ys_bzgl::cbb_med_text_changed(
        QString diag_text,
        QComboBox * cur,
        QComboBox * next,
        QComboBox * third,
        QLineEdit * dest_le,
        QComboBox * relate_tr_diag,
        QComboBox * relate_tr_symp,
        QComboBox * next_tr_diag,
        QComboBox * next_tr_symp,
        bool is_first)
{

    Q_UNUSED(next_tr_diag)
    Q_UNUSED(next_tr_symp)

    if(!initialFinished )
    {
        //当前状态不需要处理信号
        qDebug()<<"cbb_med_text_changed, 当前状态不需要处理信号\n";
        return;
    }

    initialFinished = false;

    strDiag = diag_text;
    trigTimer();

    QString code = getNatCode(diag_text, "2");//2:西医诊断，8：中医诊断

    if(code.isEmpty())
    {
        //当前诊断无效
        relate_tr_diag->setCurrentText(""); //关联的中医诊断
        relate_tr_symp->setCurrentText("");

        dest_le->clear();   //处方界面的诊断名称

        initialFinished = true;
        qDebug()<<"当前诊断 "+diag_text+ " 代码无效\n";
        return;
    }

    if(!next->currentText().isEmpty() && diag_text == next->currentText() )
        {
            QMessageBox::information(this, "注意", diag_text +" 与 next 诊断不可以重复！");
            cur->setCurrentText("");
            initialFinished = true;
            qDebug()<<"诊断 "+diag_text+ " 重复\n";
            return;
        }

    if(!third->currentText().isEmpty() && diag_text == third->currentText() )
        {
            QMessageBox::information(this, "注意", diag_text +" 与 third 诊断不可以重复！");
            cur->setCurrentText("");
            initialFinished = true;
            qDebug()<<"诊断 "+diag_text+ " 重复\n";
            return;
    }

    dest_le->setText(diag_text);

    if(!diag_model)
    {
        //不使用诊断模板
        qDebug()<<"当前系统设置为不需要诊断模版\n";
        initialFinished = true;
        return;
    }

    sq = "select "
         "med_diag_name,"   //西医诊断名称
         "med_diag_base, "   //西医诊断依据
         "tr_diag_name, "   //中医诊断名称
         "tr_symptom_name ,"    //中医证候名称
         "tr_diag_base, "   //中医诊断依据
         "tr_diag_symptom,"  //中医辩证依据
         "patient_describe,"  //主诉
         "med_now,"  //现病史
         "med_now_tr,"  //中医现病史
            "person_hist,"  //
               "menstr_hist,"  //
              "family_hist,"  //
               "person_hist,"  //
              "tr_similar_syndrom,"  //
               "tr_treatment,"
               "hist_symptom,"
               "allergy_hist,"
               "medical_advice"  //
         " from com_diag_med_tr where med_diag_code = '" + code + "'";
    sq += " and dept_code = '" + pub::dp_code + "'";

    qDebug()<<"根据西医诊断代码提取关联数据："<<sq;
    qrmt->exec(sq);

    //禁止中医诊断触发事件
    qDebug()<<"填充界面，禁止中医诊断触发事件\n";
    relate_tr_diag->blockSignals(true);
    relate_tr_symp->blockSignals(true);

    if(qrmt->next())
    {
        if(ui->rb_mode_med->isChecked() && !reload_med_rec)
        {
            //西医，非导入历史记录
            qDebug()<<"西医接诊，且非导入历史记录状态\n";
            //患者主诉
            QString str = ui->leHzzs->text();
            diag_new_model_le(ui->leHzzs, str, "患者主诉");

            //既往史
            QString tmp = ui->leJws->text().trimmed();
            if(tmp.isEmpty())
            {
                ui->leJws->setText(qrmt->value("hist_symptom").toString());
            }

            //个人史
            tmp = ui->pt_person_history->toPlainText().trimmed();
            if(tmp.isEmpty())
            {
                ui->pt_person_history->setPlainText(qrmt->value("person_hist").toString());
            }

            //月经史
            if(mpPatientInfo["sex_code"] == "F")
            {
                tmp = ui->le_menstr->text().trimmed();
                if(tmp.isEmpty())
                {
                    ui->le_menstr->setText(qrmt->value("menstr_hist").toString());
                }
            }

            //家族史
            tmp = ui->pt_family_history->toPlainText().trimmed();
            if(tmp.isEmpty())
            {
                ui->pt_family_history->setPlainText(qrmt->value("family_hist").toString());
            }

            //过敏史
            tmp = ui->leGms->text().trimmed();
            if(tmp.isEmpty())
            {
                ui->leGms->setText(qrmt->value("allergy_hist").toString());
            }

            //医嘱
            tmp = ui->pt_medical_advice->toPlainText().trimmed();
            if(tmp.isEmpty())
            {
                ui->pt_medical_advice->setPlainText(qrmt->value("medical_advice").toString());
            }

            //现病史
            QStringList med_now_list = qrmt->value("med_now").toString().split("#");
            QString med_now = med_now_list[0];
            diag_new_model(ui->pt_current_symp, med_now,"现病史");

            //专科检查
            diag_new_model(ui->pt_body_check, qrmt->value("med_diag_base").toString(),"专科检查");

        }
        else
        {
            //中医，中西医
            qDebug()<<"中医接诊，导入与西医诊断关联的中医诊断与证候名称\n";

            relate_tr_diag->clear();
            relate_tr_symp->clear();

            while(true)
            {
                QString diag = qrmt->value("tr_diag_name").toString();
                QString symp = qrmt->value("tr_symptom_name").toString();

                if(relate_tr_diag->findText( diag, Qt::MatchExactly) < 0)
                {
                    //避免插入重复项目
                    relate_tr_diag->addItem(diag);
                }

                if(relate_tr_symp->findText( symp, Qt::MatchExactly) < 0)
                {
                    //避免插入重复项目
                    relate_tr_symp->addItem(symp);
                }

                if(!qrmt->next())
                {
                    break;
                }
            }

            if(reload_med_rec)
            {
                //当前正在提取历史记录
                qDebug()<<"当前正在提取历史记录\n";
                initialFinished = true;
                relate_tr_diag->blockSignals(false);
                relate_tr_symp->blockSignals(false);
                return;
            }

            if(relate_tr_diag->count() == 1)
            {
                //列表只有一个项目则直接选中
                qDebug()<<"诊断列表只有一个项目则直接选中\n";
                relate_tr_diag->setCurrentIndex(0);
            }
            else
            {
                qDebug()<<"诊断列表项目大于1，设置当前选项空白，等待人工选取\n";
                relate_tr_symp->setCurrentIndex(-1);
            }

            //20250221修改，症候列表不再自动选中
            relate_tr_symp->setCurrentIndex(-1);

//            if(!relate_tr_symp->currentText().isEmpty()
//                    && !relate_tr_diag->currentText().isEmpty())
//            {
//                //中医诊断和症候都被选中
//                qDebug()<<"中医诊断和症候都处于有效状态，开始提取关联内容\n";
//                qrmt->first();
//                //ui->leHzzs->setText(qrmt->value("patient_describe").toString());
//                QString str = ui->leHzzs->text();
//                ui->leHzzs->setText(str + qrmt->value("patient_describe").toString());

//                //既往史
//                QString tmp = ui->leJws->text().trimmed();
//                if(tmp.isEmpty())
//                {
//                    ui->leJws->setText(qrmt->value("hist_symptom").toString());
//                }

//                //个人史
//                tmp = ui->pt_person_history->toPlainText().trimmed();
//                if(tmp.isEmpty())
//                {
//                    ui->pt_person_history->setPlainText(qrmt->value("person_hist").toString());
//                }

//                //月经史
//                if(mpPatientInfo["sex_code"] == "F")
//                {
//                    tmp = ui->le_menstr->text().trimmed();
//                    if(tmp.isEmpty())
//                    {
//                        ui->le_menstr->setText(qrmt->value("menstr_hist").toString());
//                    }
//                }


//                //家族史
//                tmp = ui->pt_family_history->toPlainText().trimmed();
//                if(tmp.isEmpty())
//                {
//                    ui->pt_family_history->setPlainText(qrmt->value("family_hist").toString());
//                }

//                //过敏史
//                tmp = ui->leGms->text().trimmed();
//                if(tmp.isEmpty())
//                {
//                    ui->leGms->setText(qrmt->value("allergy_hist").toString());
//                }


//                //医嘱
//                tmp = ui->pt_medical_advice->toPlainText().trimmed();
//                if(tmp.isEmpty())
//                {
//                    ui->pt_medical_advice->setPlainText(qrmt->value("medical_advice").toString());
//                }

//                //现病史
//                QStringList med_now_list = qrmt->value("med_now").toString().split("#");
//                QString med_now = med_now_list.join("");
//                diag_new_model(ui->pt_current_symp, med_now,"现病史");

//                //中医类证鉴别
//                diag_new_model(ui->pt_similar_syndrom, qrmt->value("tr_similar_syndrom").toString(),"中医类证鉴别");

//                //中医治则
//                diag_new_model(ui->pt_treat_tr, qrmt->value("tr_treatment").toString(),"中医治则");

//                //中医查体
//                diag_new_model(ui->pt_body_check_tr, qrmt->value("tr_diag_base").toString(),"中医查体");

//                //专科检查
//                diag_new_model(ui->pt_body_check, qrmt->value("med_diag_base").toString(),"专科检查");

//                if(is_first)
//                {
//                    diag_new_model(ui->pt_tr_diag, qrmt->value("tr_diag_symptom").toString(),"中医辩证依据");

//                }
//            }
        }
    }
    else
    {
        QMessageBox::information(this, "注意", "根据西医诊断代码提取诊断依据SQL返回无结果。");
        qDebug()<<"根据西医诊断代码提取诊断依据SQL返回无结果。\n";

        relate_tr_diag->setCurrentText("");//
        relate_tr_symp->setCurrentText("");
    }

    qDebug()<<"填充界面完成，取消禁止触发事件\n";
    relate_tr_diag->blockSignals(false);
    relate_tr_symp->blockSignals(false);
    initialFinished = true;
}

void Form_ys_bzgl::cbb_tr_diag_text_changed(
        QString diag_text,
        QComboBox *cur,
        QComboBox *next,
        QComboBox *third,
        QComboBox *cur_symp,
        QComboBox *next_symp,
        QComboBox *relate_cbb,
        QLineEdit *dest_le,
        bool is_first)
{

    Q_UNUSED(next_symp)

    if(!initialFinished)
    {
        //当前状态不需要处理信号
        qDebug()<<"initialFinished :　"<<initialFinished ;
        qDebug()<<"cbb_tr_diag_text_changed, 初始化未完成或正提取历史记录，不需要处理信号\n";
        return;
    }

    initialFinished = false;

    QString diag_code = getNatCode(diag_text, "8");  //8：中医诊断
    //QString symp_code = getNatCode(cur_symp->currentText(), "9");//9:中医证候，
    QString med_code = getNatCode(relate_cbb->currentText(), "2");//2:西医诊断

    if(med_code.isEmpty() || diag_code.isEmpty())
    {
        //tr_diag西医诊断为空，或者中医诊断为空，返回
        qDebug()<<"tr_diag西医诊断为空，或者中医诊断为空，返回\n";
        cur_symp->setCurrentText("");
        initialFinished = true;
        return;
    }

    if(!next->currentText().isEmpty() && diag_text == next->currentText() )
    {
        QMessageBox::information(this, "注意", "诊断不可以重复！");
        cur->setCurrentText("");
        cur_symp->setCurrentText("");
        initialFinished = true;
        return;
    }

    if(!third->currentText().isEmpty() && diag_text == third->currentText() )
    {
        QMessageBox::information(this, "注意", "诊断不可以重复！");
        cur->setCurrentText("");
        cur_symp->setCurrentText("");
        initialFinished = true;
        return;
    }

    cur_symp->clear();

    //整理证候列表
    sq = "select distinct tr_symptom_name "    //中医证候名称
            " from com_diag_med_tr where "
            " tr_diag_code = '" + diag_code + "'";
    sq += " and  med_diag_code = '" + med_code + "'";
    sq += " and dept_code = '" + pub::dp_code + "'";

    qDebug()<<"根据中医诊断代码提取证候名称："<<sq;
    qrmt->exec(sq);

    cur_symp->blockSignals(true);
    cur_symp->clear();
    while(qrmt->next())
    {
        cur_symp->addItem(qrmt->value("tr_symptom_name").toString());
    }
    cur_symp->setCurrentIndex(-1);
    cur_symp->blockSignals(false);

    initialFinished = true;

}

void Form_ys_bzgl::cbb_tr_symp_text_changed(
        QString diag_text,
        QComboBox *cur,
        QComboBox *next,
        QComboBox *third,
        QComboBox *cur_symp,
        QComboBox *next_symp,
        QComboBox *relate_cbb,
        QLineEdit *dest_le,
        bool is_first)
{

    Q_UNUSED(next_symp)

    if(!initialFinished || reload_med_rec)
    {
        //初始化未完成或正提取历史记录，不需要处理信号
        //qDebug()<<"initialFinished , reload_med_rec :　"<<initialFinished <<" , " <<reload_med_rec;
        qDebug()<<"cbb_tr_symp_text_changed, 初始化未完成或正提取历史记录，不需要处理信号\n";
        return;
    }

    initialFinished = false;

    QString diag_code = getNatCode(diag_text, "8");  //8：中医诊断
    QString symp_code = getNatCode(cur_symp->currentText(), "9");//9:中医证候，
    QString med_code = getNatCode(relate_cbb->currentText(), "2");//2:西医诊断

    if(med_code.isEmpty() || diag_code.isEmpty())
    {
        //西医诊断为空，或者中医诊断为空，返回
        qDebug()<<"symp西医诊断为空，或者中医诊断为空，返回\n";
        cur_symp->setCurrentText("");
        initialFinished = true;
        return;
    }

    if(!diag_model)
    {
        //不使用诊断模板
        initialFinished = true;
        return;
    }

    sq = "select "
         "med_diag_name,"   //西医诊断名称
         "med_diag_base, "   //西医诊断依据,专科检查
         "tr_diag_name, "   //中医诊断名称
         "tr_symptom_name ,"    //中医证候名称
         "tr_diag_base, "   //中医诊断依据，中医查体
         "tr_diag_symptom,"  //中医辩证依据
         "patient_describe,"  //主诉
         "med_now,"  //现病史
         "med_now_tr,"//中医现病史
         "person_hist,"  //
            "menstr_hist,"  //
           "family_hist,"  //
            "person_hist,"  //
           "tr_similar_syndrom,"  //
            "tr_treatment,"
            "hist_symptom,"
            "allergy_hist,"
            "medical_advice"  //

         " from com_diag_med_tr where tr_diag_code = '" + diag_code + "'";
    sq += " and  tr_symptom_code = '" + symp_code + "'";
    sq += " and  med_diag_code = '" + med_code + "'";
    sq += " and dept_code = '" + pub::dp_code + "'";

    qDebug()<<"根据中医诊断代码提取诊断依据："<<sq;
    qrmt->exec(sq);

    relate_cbb->blockSignals(true);
    if(qrmt->next())
    {

//        if(is_first)
//        {
//            //非第一诊断，不修改辩证
        diag_new_model(ui->pt_tr_diag, qrmt->value("tr_diag_symptom").toString(),"中医辩证依据");
        //ui->pt_tr_diag->insertPlainText(qrmt->value("tr_diag_symptom").toString());
//        }

        //患者主诉
        QString str_old = ui->leHzzs->text();
        QString str_new = qrmt->value("patient_describe").toString();
        //ui->leHzzs->setText( str_old + str_new);
        diag_new_model_le(ui->leHzzs, str_new, "患者主诉");

        //既往史
        QString tmp = ui->leJws->text().trimmed();
        if(tmp.isEmpty())
        {
            ui->leJws->setText(qrmt->value("hist_symptom").toString());
        }

        //个人史
        tmp = ui->pt_person_history->toPlainText().trimmed();
        if(tmp.isEmpty())
        {
            ui->pt_person_history->setPlainText(qrmt->value("person_hist").toString());
        }

        //月经史
        if(mpPatientInfo["sex_code"] == "F")
        {
            tmp = ui->le_menstr->text().trimmed();
            if(tmp.isEmpty())
            {
                ui->le_menstr->setText(qrmt->value("menstr_hist").toString());
            }
        }


        //家族史
        tmp = ui->pt_family_history->toPlainText().trimmed();
        if(tmp.isEmpty())
        {
            ui->pt_family_history->setPlainText(qrmt->value("family_hist").toString());
        }

        //过敏史
        tmp = ui->leGms->text().trimmed();
        if(tmp.isEmpty())
        {
            ui->leGms->setText(qrmt->value("allergy_hist").toString());
        }

        //医嘱
        tmp = ui->pt_medical_advice->toPlainText().trimmed();
        if(tmp.isEmpty())
        {
            ui->pt_medical_advice->setPlainText(qrmt->value("medical_advice").toString());
        }

        //现病史
        QStringList med_now_list = qrmt->value("med_now").toString().split("#");
        QString med_now = med_now_list.join("");
        diag_new_model(ui->pt_current_symp, med_now,"现病史");

        //中医类证鉴别
        diag_new_model(ui->pt_similar_syndrom, qrmt->value("tr_similar_syndrom").toString(),"中医类证鉴别");

        //中医治则
        diag_new_model(ui->pt_treat_tr, qrmt->value("tr_treatment").toString(),"中医治则");

        //中医查体
        diag_new_model(ui->pt_body_check_tr, qrmt->value("tr_diag_base").toString(),"中医查体");

        //专科检查
        diag_new_model(ui->pt_body_check, qrmt->value("med_diag_base").toString(),"专科检查");

    }
    else
    {
        QMessageBox::information(this, "注意", "根据中医诊断代码提取诊断依据SQL返回无结果。");
        qDebug()<<"根据中医诊断代码提取诊断依据SQL返回无结果。\n";
        relate_cbb->setCurrentText("");
    }
    relate_cbb->blockSignals(false);

    initialFinished = true;

}

void Form_ys_bzgl::diag_new_model(QPlainTextEdit *pt_edt, QString new_val, QString tip)
{
    //新增加诊断，模版处理方式选择

    QString str_old = pt_edt->toPlainText();

    if(str_old.isEmpty())
    {
        pt_edt->insertPlainText(new_val);
    }
    else
    {
        my_msg.setText("新增诊断 "+tip+" :\n" + new_val);
        my_msg.exec();

        if(my_msg.clickedButton() == bt_overwriter)
        {
            pt_edt->setPlainText(new_val);
        }
        else if(my_msg.clickedButton() == bt_append)
        {
            if(tip == "现病史")
            {
                pt_edt->appendPlainText(new_val);
            }
            else
            {
                pt_edt->insertPlainText(new_val);
            }
        }
    }
}

void Form_ys_bzgl::diag_new_model_le(QLineEdit *pt_edt, QString new_val, QString tip)
{
    //新增加诊断，模版处理方式选择

    QString str_old = pt_edt->text();

    if(str_old.isEmpty())
    {
        pt_edt->setText(new_val);
    }
    else
    {
        my_msg.setText("新增诊断 "+tip+" :\n" + new_val);
        my_msg.exec();

        if(my_msg.clickedButton() == bt_overwriter)
        {
            pt_edt->setText(new_val);
        }
        else if(my_msg.clickedButton() == bt_append)
        {
            if(tip == "现病史")
            {
                pt_edt->setText(str_old + new_val);
            }
            else
            {
                pt_edt->setText(new_val + str_old);
            }
        }
    }
}



void Form_ys_bzgl::on_le_diag1_textChanged(const QString &arg1)
{
    //if(!initialFinished) return;

    ui->leDiag1->setText(arg1);

    if(arg1.isEmpty())
    {
        ui->ckbDiag1->setChecked(false);
        //ui->ckbDiag1->setEnabled(false);
    }
    else
    {
        ui->ckbDiag1->setChecked(true);
        //ui->ckbDiag1->setEnabled(true);
    }
}

void Form_ys_bzgl::on_le_diag2_textChanged(const QString &arg1)
{
    //if(!initialFinished) return;

    ui->leDiag2->setText(arg1);

    if(arg1.isEmpty())
    {
        ui->ckbDiag2->setChecked(false);
        //ui->ckbDiag2->setEnabled(false);
    }
    else
    {
        ui->ckbDiag2->setChecked(true);
        //ui->ckbDiag2->setEnabled(true);
    }
}

void Form_ys_bzgl::on_le_diag3_textChanged(const QString &arg1)
{
    //if(!initialFinished) return;

    ui->leDiag3->setText(arg1);

    if(arg1.isEmpty())
    {
        ui->ckbDiag3->setChecked(false);
        //ui->ckbDiag3->setEnabled(false);
    }
    else
    {
        ui->ckbDiag3->setChecked(true);
        //ui->ckbDiag3->setEnabled(true);
    }
}

void Form_ys_bzgl::on_tv_aux_check_clicked(const QModelIndex &index)
{
    ui->le_item_name->setText(index.siblingAtColumn(0).data().toString());

    //医生录入的外院辅助检查项目可以删除或保存
    if(index.siblingAtColumn(2).data().toString().isNull())
    {
        ui->pb_remove->setEnabled(true);
        ui->pbSaveCK->setEnabled(true);
        ui->pt_item_result->setPlainText(index.siblingAtColumn(1).data().toString());
    }
    else
    {
        ui->pb_remove->setEnabled(false);
        if(index.siblingAtColumn(5).data().toString() == "004")
        {
            //化验项目，医生不需要录入
            ui->pbSaveCK->setEnabled(false);
        }
        else
        {
            ui->pbSaveCK->setEnabled(true);
        }
    }

    QString clinic_code = index.siblingAtColumn(4).data().toString();

    sq = " select lisitem_name,lisitem_result,lis_summary,package_name,audit_opername"
         " from met_chk_lis_result"
         " where clinic_code = '" + clinic_code + "'";// -- and hisitem_code, package_code

    qro->exec(sq);
    if(!qro->next())
    {
        return;
    }

    ui->pt_item_result->clear();

    QString result = "检验结论 ：";
    result += qro->value("lis_summary").toString() ;
    result += "\n检验技师 : ";
    result += qro->value("audit_opername").toString() ;


    for(int i = 0;; i++)
    {
        QString rec ;
        rec += qro->value("package_name").toString() ;
        rec += "/";
        rec += qro->value("lisitem_name").toString() ;
        rec += " : ";
        rec += qro->value("lisitem_result").toString() ;

        ui->pt_item_result->appendPlainText(rec);

        if(!qro->next())
        {
            break;
        }
    }

    ui->pt_item_result->appendPlainText(result);
}

void Form_ys_bzgl::on_tv_aux_check_doubleClicked(const QModelIndex &index)
{
    Q_UNUSED(index)

    on_tv_aux_check_clicked(index);
}

void Form_ys_bzgl::on_pb_remove_clicked()
{
    //删除医生录入的外院辅助检查项目

    QString atinc = ui->tv_aux_check->currentIndex().siblingAtColumn(3).data().toString();

    sq = "delete from ys_bz_e_lib where atinc = " + atinc ;
    qrm->exec(sq);

    on_tabWidget_currentChanged(2);

}

void Form_ys_bzgl::on_cbbRange_currentTextChanged(const QString &arg1)
{
    if(arg1 == "中草药")
    {
        ui->lb_tr_days->setHidden(false);
        ui->le_tr_days->setHidden(false);
        ui->le_dose_unit->setReadOnly(false);
        ui->ckb_ignore_store_sum->setHidden(false);
        ui->ckb_ignore_store_sum->setChecked(true);
    }
    else
    {
        ui->lb_tr_days->setHidden(true);
        ui->le_tr_days->setHidden(true);
        ui->le_dose_unit->setReadOnly(true);
        ui->ckb_ignore_store_sum->setHidden(true);
        ui->ckb_ignore_store_sum->setChecked(false);
    }
}

void Form_ys_bzgl::on_cbbDiag1_currentTextChanged(const QString &arg1)
{

    cbb_med_text_changed(arg1,
                         ui->cbbDiag1,ui->cbbDiag2,ui->cbbDiag3,
                         ui->le_diag1,
                         ui->cbb_tr_diag1,ui->cbb_tr_symptom1,
                         ui->cbb_tr_diag2,ui->cbb_tr_symptom2,true);

    if(diag_complete(ui->cbbDiag1, ui->cbb_tr_diag1,ui->cbb_tr_symptom1))
    {
        //ui->cbbDiag2->setEnabled(true);
       //ui->cbb_tr_diag2->setEnabled(true);
        //ui->cbb_tr_symptom2->setEnabled(true);
    }
    else
    {
        if(ui->cbbDiag2->currentText().isEmpty())
        {
            //ui->cbbDiag2->setEnabled(false);
            //ui->cbb_tr_diag2->setEnabled(false);
            //ui->cbb_tr_symptom2->setEnabled(false);
            ui->ckbDiag2->setChecked(false);
            //ui->ckbDiag2->setEnabled(false);
        }
    }

}

void Form_ys_bzgl::on_cbbDiag2_currentTextChanged(const QString &arg1)
{

    cbb_med_text_changed(arg1,
                         ui->cbbDiag2,ui->cbbDiag3,ui->cbbDiag1,
                         ui->le_diag2,
                         ui->cbb_tr_diag2,ui->cbb_tr_symptom2,
                         ui->cbb_tr_diag3,ui->cbb_tr_symptom3,false);

    if(diag_complete(ui->cbbDiag2, ui->cbb_tr_diag2,ui->cbb_tr_symptom2))
    {
        //ui->cbbDiag3->setEnabled(true);
        //ui->cbb_tr_diag3->setEnabled(true);
        //ui->cbb_tr_symptom3->setEnabled(true);
    }
    else
    {
        if(ui->cbbDiag3->currentText().isEmpty())
        {
            //ui->cbbDiag3->setEnabled(false);
            //ui->cbb_tr_diag3->setEnabled(false);
            //ui->cbb_tr_symptom3->setEnabled(false);
            ui->ckbDiag3->setChecked(false);
            //ui->ckbDiag3->setEnabled(false);
        }
    }

}

void Form_ys_bzgl::on_cbbDiag3_currentTextChanged(const QString &arg1)
{

    cbb_med_text_changed(arg1,
                         ui->cbbDiag3,ui->cbbDiag1,ui->cbbDiag2,
                         ui->le_diag3,
                         ui->cbb_tr_diag3,ui->cbb_tr_symptom3,
                         ui->cbb_tr_diag1,ui->cbb_tr_symptom1,false);
}

void Form_ys_bzgl::on_cbb_tr_diag1_currentTextChanged(const QString &arg1)
{
    cbb_tr_diag_text_changed(arg1, ui->cbb_tr_diag1, ui->cbb_tr_diag2, ui->cbb_tr_diag3,
                     ui->cbb_tr_symptom1, ui->cbb_tr_symptom2, ui->cbbDiag1,
                     ui->le_diag1, true);

    if(diag_complete(ui->cbbDiag1, ui->cbb_tr_diag1,ui->cbb_tr_symptom1))
    {
        //ui->cbbDiag2->setEnabled(true);
        //ui->cbb_tr_diag2->setEnabled(true);
        //ui->cbb_tr_symptom2->setEnabled(true);
    }
    else
    {
        if(ui->cbbDiag2->currentText().isEmpty())
        {
            //ui->cbbDiag2->setEnabled(false);
            //ui->cbb_tr_diag2->setEnabled(false);
            //ui->cbb_tr_symptom2->setEnabled(false);
            ui->ckbDiag2->setChecked(false);
            //ui->ckbDiag2->setEnabled(false);
        }
    }

}

void Form_ys_bzgl::on_cbb_tr_diag2_currentTextChanged(const QString &arg1)
{
    cbb_tr_diag_text_changed(arg1, ui->cbb_tr_diag2, ui->cbb_tr_diag3, ui->cbb_tr_diag1,
                     ui->cbb_tr_symptom2, ui->cbb_tr_symptom3, ui->cbbDiag2,
                     ui->le_diag2, false);

    if(diag_complete(ui->cbbDiag2, ui->cbb_tr_diag2,ui->cbb_tr_symptom2))
    {
        //ui->cbbDiag3->setEnabled(true);
        //ui->cbb_tr_diag3->setEnabled(true);
        //ui->cbb_tr_symptom3->setEnabled(true);
    }
    else
    {
        if(ui->cbbDiag3->currentText().isEmpty())
        {
            //ui->cbbDiag3->setEnabled(false);
            //ui->cbb_tr_diag3->setEnabled(false);
            //ui->cbb_tr_symptom3->setEnabled(false);
            ui->ckbDiag3->setChecked(false);
            //ui->ckbDiag3->setEnabled(false);
        }
    }
}

void Form_ys_bzgl::on_cbb_tr_diag3_currentTextChanged(const QString &arg1)
{

    cbb_tr_diag_text_changed(arg1, ui->cbb_tr_diag3, ui->cbb_tr_diag1, ui->cbb_tr_diag2,
                     ui->cbb_tr_symptom3, ui->cbb_tr_symptom1, ui->cbbDiag3,
                     ui->le_diag3, false);
}

void Form_ys_bzgl::on_cbb_tr_symptom1_currentTextChanged(const QString &arg1)
{

    if(arg1.isEmpty())
    {
        return;
    }

    QString diag = ui->cbb_tr_diag1->currentText();

    cbb_tr_symp_text_changed(diag, ui->cbb_tr_diag1, ui->cbb_tr_diag2, ui->cbb_tr_diag3,
                     ui->cbb_tr_symptom1, ui->cbb_tr_symptom2, ui->cbbDiag1,
                     ui->le_diag1, true);

    if(diag_complete(ui->cbbDiag1, ui->cbb_tr_diag1,ui->cbb_tr_symptom1))
    {
        //ui->cbbDiag2->setEnabled(true);
        //ui->cbb_tr_diag2->setEnabled(true);
        //ui->cbb_tr_symptom2->setEnabled(true);
    }
    else
    {
        if(ui->cbbDiag2->currentText().isEmpty())
        {
            //ui->cbbDiag2->setEnabled(false);
            //ui->cbb_tr_diag2->setEnabled(false);
            //ui->cbb_tr_symptom2->setEnabled(false);
            ui->ckbDiag2->setChecked(false);
            //ui->ckbDiag2->setEnabled(false);
        }
    }
}

void Form_ys_bzgl::on_cbb_tr_symptom2_currentTextChanged(const QString &arg1)
{

    if(arg1.isEmpty())
    {
        return;
    }

    QString diag = ui->cbb_tr_diag2->currentText();
    cbb_tr_symp_text_changed(diag, ui->cbb_tr_diag2, ui->cbb_tr_diag3, ui->cbb_tr_diag1,
                     ui->cbb_tr_symptom2, ui->cbb_tr_symptom3, ui->cbbDiag2,
                     ui->le_diag2, false);

    if(diag_complete(ui->cbbDiag2, ui->cbb_tr_diag2,ui->cbb_tr_symptom2))
    {
        //ui->cbbDiag3->setEnabled(true);
        //ui->cbb_tr_diag3->setEnabled(true);
        //ui->cbb_tr_symptom3->setEnabled(true);
    }
    else
    {
        if(ui->cbbDiag3->currentText().isEmpty())
        {
            //ui->cbbDiag3->setEnabled(false);
            //ui->cbb_tr_diag3->setEnabled(false);
            //ui->cbb_tr_symptom3->setEnabled(false);
            ui->ckbDiag3->setChecked(false);
            //ui->ckbDiag3->setEnabled(false);
        }
    }
}

void Form_ys_bzgl::on_cbb_tr_symptom3_currentTextChanged(const QString &arg1)
{

    if(arg1.isEmpty())
    {
        return;
    }

    QString diag = ui->cbb_tr_diag3->currentText();
    cbb_tr_symp_text_changed(diag, ui->cbb_tr_diag3, ui->cbb_tr_diag1, ui->cbb_tr_diag2,
                     ui->cbb_tr_symptom3, ui->cbb_tr_symptom1, ui->cbbDiag3,
                     ui->le_diag3, false);

}

bool Form_ys_bzgl::diag_complete(QComboBox *med_diag, QComboBox *tr_diag,QComboBox *tr_symp)
{
    if(ui->rb_mode_tr->isChecked() || ui->rb_mode_tr_med->isChecked())
    {
        //中医或中西医
        if(!med_diag->currentText().isEmpty()
                && !tr_diag->currentText().isEmpty()
                && !tr_symp->currentText().isEmpty()
                )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        //西医
        if(med_diag->currentText().isEmpty())
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}

void Form_ys_bzgl::on_pb_clear_base_clicked()
{
    //清除病志
    initialFinished = false;
    ui->cbbReason->setCurrentIndex(-1);   //就诊原因

    sq = "select item_name from com_dict_icpc where instr(dept_code, '"
            + pub::dp_code + "') > 0 and type = '2' order by convert(item_name using gbk)";

    fillCombo(ui->cbbDiag1, sq, -1);   //诊断 1
    fillCombo(ui->cbbDiag2, sq, -1);   //诊断 2
    fillCombo(ui->cbbDiag3, sq, -1);   //诊断 3

    //ui->cbbDiag2->setEnabled(false);
    //ui->cbbDiag3->setEnabled(false);

    //ui->cbb_tr_diag2->setEnabled(false);
    //ui->cbb_tr_diag3->setEnabled(false);

    //ui->cbb_tr_symptom2->setEnabled(false);
    //ui->cbb_tr_symptom3->setEnabled(false);

    if(!ui->rb_mode_med->isChecked())
    {
        //非西医模式
        sq = "select item_name from com_dict_icpc where instr(dept_code, '"
                + pub::dp_code + "') > 0 and type = '8' order by convert(item_name using gbk)";

        fillCombo(ui->cbb_tr_diag1, sq, -1);   //中医主诊断
        fillCombo(ui->cbb_tr_diag2, sq, -1);   //中医诊断2
        fillCombo(ui->cbb_tr_diag3, sq, -1);   //中医诊断3
        ui->cbb_tr_symptom1->setCurrentIndex(-1);
        ui->cbb_tr_symptom2->setCurrentIndex(-1);
        ui->cbb_tr_symptom3->setCurrentIndex(-1);
    }

    ui->pt_tr_diag->clear();

    ui->pt_similar_syndrom->clear();
    ui->le_menstr->clear();
    ui->pt_family_history->clear();
    ui->pt_person_history->clear();
    ui->pt_treat_tr->clear();
    ui->pt_medical_advice->clear();

    //ui->ckbDiag1->setEnabled(false);
    //ui->ckbDiag2->setEnabled(false);
    //ui->ckbDiag3->setEnabled(false);

    ui->leDiag1->clear();   //主诊断
    ui->leDiag2->clear();   //诊断2
    ui->leDiag3->clear();   //诊断3
    ui->le_diag1->clear();
    ui->le_diag2->clear();
    ui->le_diag3->clear();

    ui->cbbTrusteeRlt->setCurrentIndex(-1);//代取药人关系
    ui->leTrustee->clear();
    ui->leTrusteeI->clear();
    ui->leTrusteeP->clear();

    ui->ckb_no_patient->setChecked(false); //患者未亲自就诊

    ui->cbbBzmb->setCurrentIndex(-1);//病志模板
    ui->cbbGms->setCurrentIndex(-1);//过敏
    ui->cbbJws->setCurrentIndex(-1);//既往
    ui->cbbJchy->setCurrentIndex(-1);
    ui->cbb_conclusion->setCurrentIndex(0); //诊疗结论

    ui->le_next_call->clear();
    ui->le_wx_name->clear();
    ui->pt_all_result->clear();
    ui->pt_aux_check->clear();
    ui->pt_item_result->clear();
    ui->leHzzs->clear();//患者主诉
    ui->pt_current_symp->clear();//现病史
    ui->pt_similar_syndrom->clear();//类证
    ui->pt_treat_tr->clear();//治则
    ui->leGms->clear();//过敏史
    ui->leJws->clear();//既往史
    ui->pt_body_check->clear();//体格检查
    ui->pt_body_check_tr->clear();//体格检查

    ui->pb_remove->setEnabled(false);

    ui->le_tr_days->clear(); //草药剂数
    ui->le_dose_unit->setReadOnly(true);    //用量单位，草药需要单独录入

    ui->cbbRange->setCurrentIndex(0);

    initialFinished = true;
}

void Form_ys_bzgl::on_pb_2261_clicked()
{

    qDebug()<<"单独保存代取药信息："<<sq;
    if((ui->leTrustee->text().trimmed().isEmpty()
        || ui->leTrusteeI->text().trimmed().isEmpty()
        || ui->leTrusteeP->text().trimmed().isEmpty())
        || ui->cbbTrusteeRlt->currentText().trimmed().isEmpty())
    {
        //busi_2261 对全空不执行操作，但返回 true，所以这里要再判断一下

        QMessageBox::information(this, "注意", "代开药人信息录入完整才可以保存！");
        return;
    }

    sq = " update ys_bz_e_rec e set ";
    sq += " trustee_name = '" + ui->leTrustee->text().trimmed() + "',";
    sq += " trustee_tel = '" + ui->leTrusteeP->text().trimmed() + "',";
    sq += " trustee_certno = '" + ui->leTrusteeI->text().trimmed() + "',";
    sq += " rlts = '" + ui->cbbTrusteeRlt->currentText() + "'";
    sq += " where clinic_code = '" + mpPatientInfo["clinic_code"] + "' ";

    qrm->exec(sq);

    if(mpPatientInfo["pact_code"] == "2" && !busi_2261())
    {
        //医保患者需要进行 2261 交易
        QMessageBox::information(this, "注意", "保存代开药人医保交易失败！");
        return;
    }

    QMessageBox::information(this, "注意", "保存代开药人信息操作完成！");

}

bool Form_ys_bzgl::busi_2261()
{

    if((ui->leTrustee->text().trimmed().isEmpty()
        && ui->leTrusteeI->text().trimmed().isEmpty()
        && ui->leTrusteeP->text().trimmed().isEmpty()))
    {
        //全空
    }
    else if (!ui->leTrustee->text().trimmed().isEmpty()
             && !ui->leTrusteeI->text().trimmed().isEmpty()
             && !ui->leTrusteeP->text().trimmed().isEmpty()
             && !ui->cbbTrusteeRlt->currentText().trimmed().isEmpty() )
    {
        //全非空
        char id[20];
        QByteArray id0 = ui->leTrusteeI->text().toLocal8Bit();
        memcpy(id, id0, id0.size() +1 );

        if(!pub::verifyIdCard(id))
        {
            QMessageBox::warning(this,"错误","代取药人身份证号有效性校验失败！");
            return false;
        }

        QString phone = ui->leTrusteeP->text().trimmed();
        if ( qFuzzyCompare( phone.toDouble() ,0))
        {
            QMessageBox::warning(this,"错误","代取药人手机号包含非数字字符！");
            return false;
        }
        if(phone.length() != 11)
        {
            QMessageBox::warning(this,"错误","代取药人手机号位数无效！");
            return false;
        }

        if((mpPatientInfo["pact_code"] == "2") && !call_2261() )
        {
            //医保患者调用代取药上传交易，非医保只保存信息不上传
            return false;
        }
    }
    else
    {
        //if(ui->tab_recipe_new->isHidden())
        QMessageBox::information(this, "注意", "代开药人信息必须录入完整或全空！");
        return false;
    }

    return true;

}

void Form_ys_bzgl::diag1_state_enable()
{

    ui->cbbDiag1->setCurrentText(ui->cbbDiag2->currentText());
    ui->cbb_tr_diag1->setCurrentText(ui->cbb_tr_diag2->currentText());
    ui->cbb_tr_symptom1->setCurrentText(ui->cbb_tr_symptom2->currentText());
    ui->le_diag1->setText(ui->cbbDiag2->currentText());
    ui->ckbDiag1->setEnabled(true);
    ui->ckbDiag1->setChecked(true);

}

void Form_ys_bzgl::diag2_state_enable()
{
    ui->cbbDiag2->setCurrentText(ui->cbbDiag3->currentText());
    ui->cbb_tr_diag2->setCurrentText(ui->cbb_tr_diag3->currentText());
    ui->cbb_tr_symptom2->setCurrentText(ui->cbb_tr_symptom3->currentText());
    ui->le_diag2->setText(ui->cbbDiag3->currentText());
    //ui->ckbDiag2->setEnabled(true);
    ui->ckbDiag2->setChecked(true);

}

void Form_ys_bzgl::diag2_state_disable()
{
    ui->cbbDiag2->setCurrentText("");
    ui->cbb_tr_diag2->setCurrentText("");
    ui->cbb_tr_symptom2->setCurrentText("");
    ui->le_diag2->setText("");
    //ui->ckbDiag2->setEnabled(false);
    ui->ckbDiag2->setChecked(false);
}

void Form_ys_bzgl::diag3_state_disable()
{
    ui->cbbDiag3->setCurrentText("");
    ui->cbb_tr_diag3->setCurrentText("");
    ui->cbb_tr_symptom3->setCurrentText("");
    ui->le_diag3->setText("");
    //ui->ckbDiag3->setEnabled(false);
    ui->ckbDiag3->setChecked(false);
}

QMap<QString, QString> Form_ys_bzgl::config_diag(QMap<QString, QString> cur)
{
    //多次保存病志，处理多诊断，清理无效诊断

    QMap<QString,QString> diags;

    //提取上一次与药品关联的诊断
    QString cur_diags, tmp_sql;

    tmp_sql = "select distinct clinicdiag_name,clinicotherdiag1_name,"
              " clinicotherdiag2_name "
              " from met_ord_recipedetail "
              " where clinic_code = '%1' " //指定的 clinic_code
            " and status in ('0', '1') " //未退
            " and drug_flag in('1','4')" //西药中成， 或草药
            ;

    tmp_sql = tmp_sql.arg(cur["clinic_code"]);

    qDebug()<<"提取上一次与药品关联的诊断："<<tmp_sql;

    qrot->exec(tmp_sql);
    while(qrot->next())
    {
        cur_diags.append(qrot->value(0).toString());
        cur_diags.append("^");
        cur_diags.append(qrot->value(1).toString());
        cur_diags.append("^");
        cur_diags.append(qrot->value(2).toString());
        cur_diags.append("^");

    }

    qDebug()<<"与药品关联诊断名称 : "<<cur_diags;

    //检查当前存储的诊断是否与药品相关，如不相关则不保存

    int sn = 1;
    if(!cur["zd1"].isEmpty())
    {
        if(cur_diags.indexOf( cur["zd1"] ) >= 0)
        {
            diags["zd"+QString::number(sn)] = cur["zd1"];
            diags["zd"+QString::number(sn)+"c"] = cur["zd1c"];
            diags["zyzd"+QString::number(sn)] = cur["zyzd1"];
            diags["zyzd"+QString::number(sn)+"c"] = cur["zyzd1c"];
            diags["zyzh"+QString::number(sn)] = cur["zyzh1"];
            diags["zyzh"+QString::number(sn)+"c"] = cur["zyzh1c"];
            sn++;
        }
    }

    if(!cur["zd2"].isEmpty())
    {
        if(cur_diags.indexOf( cur["zd2"] ) >= 0)
        {
            diags["zd"+QString::number(sn)] = cur["zd2"];
            diags["zd"+QString::number(sn)+"c"] = cur["zd2c"];
            diags["zyzd"+QString::number(sn)] = cur["zyzd2"];
            diags["zyzd"+QString::number(sn)+"c"] = cur["zyzd2c"];
            diags["zyzh"+QString::number(sn)] = cur["zyzh2"];
            diags["zyzh"+QString::number(sn)+"c"] = cur["zyzh2c"];
            sn++;
        }
    }

    if(!cur["zd3"].isEmpty())
    {
        if(cur_diags.indexOf( cur["zd3"] ) >= 0)
        {
            diags["zd"+QString::number(sn)] = cur["zd3"];
            diags["zd"+QString::number(sn)+"c"] = cur["zd3c"];
            diags["zyzd"+QString::number(sn)] = cur["zyzd3"];
            diags["zyzd"+QString::number(sn)+"c"] = cur["zyzd3c"];
            diags["zyzh"+QString::number(sn)] = cur["zyzh3"];
            diags["zyzh"+QString::number(sn)+"c"] = cur["zyzh3c"];
            sn++;
        }
    }
    qDebug()<<"上次的有效诊断 : "<<diags;

    //本次录入，上次未保存过的诊断
    if(!ui->cbbDiag1->currentText().isEmpty())
    {

        int idx = cur_diags.indexOf( ui->cbbDiag1->currentText());
        if( idx < 0)
        {
            //has not saved, then save it.
            diags["zd"+QString::number(sn)] = ui->cbbDiag1->currentText();
            diags["zd"+QString::number(sn)+"c"] = getNatCode(ui->cbbDiag1->currentText(), "2");
            diags["zyzd"+QString::number(sn)] = ui->cbb_tr_diag1->currentText();
            diags["zyzd"+QString::number(sn)+"c"] = getNatCode(ui->cbb_tr_diag1->currentText(), "8");
            diags["zyzh"+QString::number(sn)] = ui->cbb_tr_symptom1->currentText();
            diags["zyzh"+QString::number(sn)+"c"] = getNatCode(ui->cbb_tr_symptom1->currentText(), "9");
            sn++;
        }
        else
        {
            //has been saved, then update it.
            diags["zd"+QString::number(idx+1)] = ui->cbbDiag1->currentText();
            diags["zd"+QString::number(idx+1)+"c"] = getNatCode(ui->cbbDiag1->currentText(), "2");
            diags["zyzd"+QString::number(idx+1)] = ui->cbb_tr_diag1->currentText();
            diags["zyzd"+QString::number(idx+1)+"c"] = getNatCode(ui->cbb_tr_diag1->currentText(), "8");
            diags["zyzh"+QString::number(idx+1)] = ui->cbb_tr_symptom1->currentText();
            diags["zyzh"+QString::number(idx+1)+"c"] = getNatCode(ui->cbb_tr_symptom1->currentText(), "9");

        }
    }

    if(!ui->cbbDiag2->currentText().isEmpty())
    {
        int idx = cur_diags.indexOf( ui->cbbDiag2->currentText());
        if( idx < 0)
        {
            diags["zd"+QString::number(sn)] = ui->cbbDiag2->currentText();
            diags["zd"+QString::number(sn)+"c"] = getNatCode(ui->cbbDiag2->currentText(), "2");
            diags["zyzd"+QString::number(sn)] = ui->cbb_tr_diag2->currentText();
            diags["zyzd"+QString::number(sn)+"c"] = getNatCode(ui->cbb_tr_diag2->currentText(), "8");
            diags["zyzh"+QString::number(sn)] = ui->cbb_tr_symptom2->currentText();
            diags["zyzh"+QString::number(sn)+"c"] = getNatCode(ui->cbb_tr_symptom2->currentText(), "9");
            sn++;
        }
        else
        {
            //has been saved, then update it.
            diags["zd"+QString::number(idx+1)] = ui->cbbDiag1->currentText();
            diags["zd"+QString::number(idx+1)+"c"] = getNatCode(ui->cbbDiag1->currentText(), "2");
            diags["zyzd"+QString::number(idx+1)] = ui->cbb_tr_diag1->currentText();
            diags["zyzd"+QString::number(idx+1)+"c"] = getNatCode(ui->cbb_tr_diag1->currentText(), "8");
            diags["zyzh"+QString::number(idx+1)] = ui->cbb_tr_symptom1->currentText();
            diags["zyzh"+QString::number(idx+1)+"c"] = getNatCode(ui->cbb_tr_symptom1->currentText(), "9");

        }
    }

    if(!ui->cbbDiag3->currentText().isEmpty())
    {
        int idx = cur_diags.indexOf( ui->cbbDiag3->currentText());
        if( idx < 0)
        {
            diags["zd"+QString::number(sn)] = ui->cbbDiag3->currentText();
            diags["zd"+QString::number(sn)+"c"] = getNatCode(ui->cbbDiag3->currentText(), "2");
            diags["zyzd"+QString::number(sn)] = ui->cbb_tr_diag3->currentText();
            diags["zyzd"+QString::number(sn)+"c"] = getNatCode(ui->cbb_tr_diag3->currentText(), "8");
            diags["zyzh"+QString::number(sn)] = ui->cbb_tr_symptom3->currentText();
            diags["zyzh"+QString::number(sn)+"c"] = getNatCode(ui->cbb_tr_symptom3->currentText(), "9");
            sn++;
        }
        else
        {
            //has been saved, then update it.
            diags["zd"+QString::number(idx+1)] = ui->cbbDiag1->currentText();
            diags["zd"+QString::number(idx+1)+"c"] = getNatCode(ui->cbbDiag1->currentText(), "2");
            diags["zyzd"+QString::number(idx+1)] = ui->cbb_tr_diag1->currentText();
            diags["zyzd"+QString::number(idx+1)+"c"] = getNatCode(ui->cbb_tr_diag1->currentText(), "8");
            diags["zyzh"+QString::number(idx+1)] = ui->cbb_tr_symptom1->currentText();
            diags["zyzh"+QString::number(idx+1)+"c"] = getNatCode(ui->cbb_tr_symptom1->currentText(), "9");

        }
    }

    qDebug()<<"本次保存之后的有效诊断 : "<<diags;

    if(sn > 4)
    {
        QMessageBox::information(this, "注意", "诊断最多可以保存3项，超出部分将不会保存。");
    }

    return diags;
}

void Form_ys_bzgl::on_pb_save_doct_ord_clicked()
{
    if( !mpPatientInfo["see_docd"].isEmpty() && mpPatientInfo["see_docd"] != pub::usr_code)
    {
        QMessageBox::information(this, "注意", "非本人接诊记录，不能修改！");
        return ;
    }

    sq = " update ys_bz_e_rec e set yz = '" + ui->pt_medical_advice->toPlainText() + "'";
    sq += " where clinic_code = '" + mpPatientInfo["clinic_code"] + "' ";

    qDebug()<<"修改保存病志记录-医嘱 ："<<sq;
    qrm->exec(sq);

    QMessageBox::information(this, "注意", "保存医嘱信息操作完成！");

}

void Form_ys_bzgl::on_ckb_refine_recorder_clicked()
{
    on_pbFresh_clicked();
}

void Form_ys_bzgl::on_pb_get_history_clicked()
{
    sq = " select to_char(reg_date, 'yyyy-mm-dd') 日期, "
         " (select empl_name "
         "    from com_employee em "
         "    where em.empl_code = a.see_docd"
         " ) 医生姓名,"
         " clinic_code 就诊ID "
         " from FIN_OPR_REGISTER a "
         " where "
         " valid_flag = '1' "
         " and dept_code = '"+ pub::dp_code+"' ";
    sq += " and card_no = '" + mpPatientInfo["card_no"] + "' ";
    sq += " order by reg_date desc ";

    qDebug()<<"提取历史病志信息 : " << sq;
    mdSearchPop->setQuery( sq , pub::db_o);

    if(mdSearchPop->rowCount() < 2)
    {
        QMessageBox::information(this, "注意", "找不到有效的历史记录！");
        return;
    }

    dlgGetItem->setDisplay(*mdSearchPop,QRect(300, 150, 800, 500),"","0.3^0.3^0.3^0^0");
    dlgGetItem->setModal(true);
    dlgGetItem->exec();

    QString popRetStr = dlgGetItem->retStr();
    if(popRetStr.isEmpty())
    {
        return;
    }
    qDebug()<<"pop select return value is : "<<popRetStr;

    QString clinic_code_tmp = pub::getStr(popRetStr, "^", 3);

    //病志相关信息
    sq = " select * from ys_bz_e_rec where clinic_code = '" + clinic_code_tmp + "' ";

    qDebug()<<"提取最后一次挂号关联的病志相关信息 : "<<sq;

    qrm->exec(sq);
    qrm->next();
    QString diag1,diag2,diag3;

    initialFinished = false;
    ui->leHzzs->setText(qrm->value("hzzs").toString());
    ui->pt_current_symp->setPlainText(qrm->value("xbs").toString());
    ui->leJws->setText(qrm->value("jws").toString());
    ui->leGms->setText(qrm->value("gms").toString());
    ui->pt_body_check->insertPlainText(qrm->value("tgjc").toString());
    ui->pt_medical_advice->setPlainText(qrm->value("yz").toString());
    ui->cbbReason->setCurrentText( qrm->value("jzyy").toString() );

    ui->le_menstr->setText(qrm->value("menstr_hist").toString());
    ui->pt_person_history->insertPlainText(qrm->value("person_hist").toString());
    ui->pt_family_history->insertPlainText(qrm->value("family_hist").toString());

    diag1 = qrm->value("zd1").toString();
    diag2 = qrm->value("zd2").toString();
    diag3 = qrm->value("zd3").toString();
    if(!diag1.isEmpty())
    {
        ui->cbbDiag1->setCurrentText(diag1);
        ui->leDiag1->setText(diag1);
        ui->le_diag1->setText(diag1);
        ui->ckbDiag1->setEnabled(true);
        ui->ckbDiag1->setChecked(true);
    }

    if(!diag2.isEmpty())
    {
        ui->cbbDiag2->setEnabled(true);
        ui->cbbDiag2->setCurrentText(diag2);
        ui->leDiag2->setText(diag2);
        ui->le_diag2->setText(diag2);
        ui->ckbDiag2->setEnabled(true);
        ui->ckbDiag2->setChecked(true);
    }

    if(!diag3.isEmpty())
    {
        ui->cbbDiag3->setEnabled(true);
        ui->cbbDiag3->setCurrentText(diag3);
        ui->leDiag3->setText(diag3);
        ui->le_diag3->setText(diag3);
        ui->ckbDiag3->setEnabled(true);
        ui->ckbDiag3->setChecked(true);
    }

    if(ui->rb_mode_tr->isChecked() || ui->rb_mode_tr_med->isChecked())
    {
        //中医或中西医, 提取上次的中医相关内容

        ui->pt_body_check_tr->insertPlainText(qrm->value("tgjc_tr").toString());
        ui->pt_similar_syndrom->setPlainText(qrm->value("similar_syndrom").toString());
        ui->pt_treat_tr->setPlainText(qrm->value("treat_tr").toString());

        ui->cbb_tr_diag1->setCurrentText( qrm->value("zyzd1").toString() );
        ui->cbb_tr_diag2->setCurrentText( qrm->value("zyzd2").toString() );
        ui->cbb_tr_diag3->setCurrentText( qrm->value("zyzd3").toString() );

        ui->cbb_tr_symptom1->setCurrentText( qrm->value("zyzh1").toString() );
        ui->cbb_tr_symptom2->setCurrentText( qrm->value("zyzh2").toString() );
        ui->cbb_tr_symptom3->setCurrentText( qrm->value("zyzh3").toString() );

        ui->pt_tr_diag->setPlainText(qrm->value("zybz").toString());

        ui->cbb_conclusion->setCurrentText(qrm->value("zljl").toString());
        if(ui->cbb_conclusion->currentText().isEmpty())
        {
            ui->cbb_conclusion->setCurrentIndex(0);
        }
    }

    initialFinished = true;

}

void Form_ys_bzgl::on_pb_alter_diag_clicked()
{
    //变更已开处方的诊断

    if(!ui->tvRecipe->currentIndex().isValid())
    {
        QMessageBox::information(this, "注意", "未选定有效数据行！");
        return;
    }

    if(!ui->ckb_leDiag1->isChecked()
            && !ui->ckb_leDiag2->isChecked()
            && !ui->ckb_leDiag3->isChecked()
            )
    {
        QMessageBox::information(this, "注意", "未指定新的诊断！");
        return;
    }

    QString itemseq = ui->tvRecipe->currentIndex().siblingAtColumn(9).data().toString();

    QMessageBox::StandardButton result;
    result = QMessageBox::warning(NULL, "注意", "确定要变更已经存在的诊断关联？",QMessageBox::Yes|QMessageBox::No);

    if(result != QMessageBox::Yes)
    {
        return;
    }

    QString diags = "";

    if(ui->ckb_leDiag1->isChecked())
    {
        diags += ui->leDiag1->text()
                + "^"
                + getNatCode( ui->leDiag1->text(), "2" )
                + "^";
    }

    if(ui->ckb_leDiag2->isChecked())
    {
        diags += ui->leDiag2->text()
                + "^"
                + getNatCode( ui->leDiag2->text(), "2" )
                + "^";
    }

    if(ui->ckb_leDiag3->isChecked())
    {
        diags += ui->leDiag3->text()
                + "^"
                + getNatCode( ui->leDiag3->text(), "2" )
                + "^";
    }

    //诊间处方表
    sq = "update met_ord_recipedetail set ";
    sq += "CLINICDIAG_NAME = '" + pub::getStr(diags, "^", 1) + "',";        //主诊断名
    sq += "CLINICDIAG_CODE = '" + pub::getStr(diags, "^", 2) + "',";       //主诊断编码
    sq += "CLINICOTHERDIAG1_NAME = '" + pub::getStr(diags, "^", 3) + "',";  //
    sq += "CLINICOTHERDIAG1_CODE = '" + pub::getStr(diags, "^", 4) + "',"; //
    sq += "CLINICOTHERDIAG2_NAME = '" + pub::getStr(diags, "^", 5) + "',";  //
    sq += "CLINICOTHERDIAG2_CODE = '" + pub::getStr(diags, "^", 6) + "'"; //
    sq += " where sequence_no = '" + itemseq + "'";
    qro->exec(sq);

    qDebug()<<"变更已经开具处方的诊断："<<sq;

    fresh_e_rec_zd();
    getRegDateRecipe();

}

void Form_ys_bzgl::on_tb_exchange_diag0_clicked()
{

    QList<QString> all_diags;//当前界面上显示的诊断信息
    QString diag;

    all_diags << ui->cbbDiag1->currentText() ;
    all_diags << ui->cbb_tr_diag1->currentText() ;
    all_diags << ui->cbb_tr_symptom1->currentText() ;

    all_diags << ui->cbbDiag2->currentText();
    all_diags << ui->cbb_tr_diag2->currentText() ;
    all_diags << ui->cbb_tr_symptom2->currentText();

    initialFinished = false;
    restore_diag_comb("110");//恢复一二列

    ui->cbbDiag1->setCurrentText(all_diags[3]);
    ui->cbb_tr_diag1->setCurrentText(all_diags[4]);
    ui->cbb_tr_symptom1->setCurrentText(all_diags[5]);
    ui->le_diag1->setText(all_diags[3]);
    ui->ckbDiag1->setEnabled(true);

    ui->cbbDiag2->setCurrentText(all_diags[0]);
    ui->cbb_tr_diag2->setCurrentText(all_diags[1]);
    ui->cbb_tr_symptom2->setCurrentText(all_diags[2]);
    ui->le_diag2->setText(all_diags[0]);
    ui->ckbDiag2->setEnabled(true);

    initialFinished = true;
}

void Form_ys_bzgl::on_tb_exchange_diag1_clicked()
{

    QList<QString> all_diags;//当前界面上显示的诊断信息
    QString diag;

    all_diags << ui->cbbDiag2->currentText() ;
    all_diags << ui->cbb_tr_diag2->currentText() ;
    all_diags << ui->cbb_tr_symptom2->currentText() ;

    all_diags << ui->cbbDiag3->currentText();
    all_diags << ui->cbb_tr_diag3->currentText() ;
    all_diags << ui->cbb_tr_symptom3->currentText();

    initialFinished = false;
    restore_diag_comb("011");//恢复二三列

    ui->cbbDiag2->setCurrentText(all_diags[3]);
    ui->cbb_tr_diag2->setCurrentText(all_diags[4]);
    ui->cbb_tr_symptom2->setCurrentText(all_diags[5]);
    ui->le_diag2->setText(all_diags[3]);
    ui->ckbDiag2->setEnabled(true);

    ui->cbbDiag3->setCurrentText(all_diags[0]);
    ui->cbb_tr_diag3->setCurrentText(all_diags[1]);
    ui->cbb_tr_symptom3->setCurrentText(all_diags[2]);
    ui->le_diag3->setText(all_diags[0]);
    ui->ckbDiag3->setEnabled(true);

    initialFinished = true;

}

void Form_ys_bzgl::on_pb_fresh_diag_clicked()
{

    /*
    整理流程：
    1、提取本次就诊已经保存的诊断；
    2、诊断存入 List，同时排除重复记录。
    3、对当前界面诊断逐一判断，不重复则保存，重复则用界面替换已保存
    */

    QString tmp_sql;
    QList<QString> all_diags;
    QList<QString> key_diags;
    QString diag;

    if(!ui->ckb_final_diag->isChecked())
    {
        //未勾选最终诊断，提取已经保存诊断

        tmp_sql = " select zd1, zd1c, zd2, zd2c, zd3, zd3c,"//诊断，代码
                " zyzd1, zyzd2, zyzd3, zyzh1, zyzh2, zyzh3, "//中医诊断，代码
                " zyzd1c, zyzd2c, zyzd3c, zyzh1c, zyzh2c, zyzh3c "//中医诊断，代码
                " from ys_bz_e_rec where clinic_code = '%1' ";

        tmp_sql = tmp_sql.arg(mpPatientInfo["clinic_code"]);

        qDebug()<<"提取上一次诊断："<<tmp_sql;

        qrmt->exec(tmp_sql);
        if(qrmt->next())
        {

            diag = qrmt->value("zd1").toString() + "^";
            diag += qrmt->value("zd1c").toString() + "^";
    //        diag += qrmt->value("zyzd1").toString() + "^";
    //        diag += qrmt->value("zyzd1c").toString() + "^";

    //        if(diag != "^^^^")
    //        {

            if(diag != "^^")
            {

                key_diags << diag;

                diag += qrmt->value("zyzd1").toString() + "^";
                diag += qrmt->value("zyzd1c").toString() + "^";

                diag += qrmt->value("zyzh1").toString() + "^";
                diag += qrmt->value("zyzh1c").toString();

                all_diags << diag;
            }

            diag = qrmt->value("zd2").toString() + "^";
            diag += qrmt->value("zd2c").toString() + "^";

            if(diag != "^^" && key_diags.indexOf(diag) < 0)
            {
                key_diags << diag;

                diag += qrmt->value("zyzd2").toString() + "^";
                diag += qrmt->value("zyzd2c").toString() + "^";

                diag += qrmt->value("zyzh2").toString() + "^";
                diag += qrmt->value("zyzh2c").toString();

                all_diags << diag;
            }

            diag = qrmt->value("zd3").toString() + "^";
            diag += qrmt->value("zd3c").toString() + "^";

            if(diag != "^^" && key_diags.indexOf(diag) < 0)
            {
                key_diags << diag;

                diag += qrmt->value("zyzd3").toString() + "^";
                diag += qrmt->value("zyzd3c").toString() + "^";

                diag += qrmt->value("zyzh3").toString() + "^";
                diag += qrmt->value("zyzh3c").toString();

                all_diags << diag;
            }

            qDebug()<<"已经保存的诊断 : "<<all_diags;
        }
        else
        {
            qDebug()<<"当前 clinic code 无保存诊断  ";
        }

    }


    //当前界面上的诊断

    if(!ui->cbbDiag1->currentText().isEmpty())
    {
        diag = ui->cbbDiag1->currentText() + "^";
        diag += getNatCode(ui->cbbDiag1->currentText(), "2") + "^";

        int idx = key_diags.indexOf(diag);

        if(idx < 0)
        {
            key_diags << diag;

            diag += ui->cbb_tr_diag1->currentText() + "^";
            diag += getNatCode(ui->cbb_tr_diag1->currentText(), "8") + "^";

            diag += ui->cbb_tr_symptom1->currentText() + "^";
            diag += getNatCode(ui->cbb_tr_symptom1->currentText(), "9");

            all_diags << diag;
        }
        else
        {

            diag += ui->cbb_tr_diag1->currentText() + "^";
            diag += getNatCode(ui->cbb_tr_diag1->currentText(), "8") + "^";

            diag += ui->cbb_tr_symptom1->currentText() + "^";
            diag += getNatCode(ui->cbb_tr_symptom1->currentText(), "9");

            all_diags[idx] = diag;

        }

    }

    if(!ui->cbbDiag2->currentText().isEmpty())
    {
        diag = ui->cbbDiag2->currentText() + "^";
        diag += getNatCode(ui->cbbDiag2->currentText(), "2") + "^";

        int idx = key_diags.indexOf(diag);

        if( idx < 0)
        {
            key_diags << diag;

            diag += ui->cbb_tr_diag2->currentText() + "^";
            diag += getNatCode(ui->cbb_tr_diag2->currentText(), "8") + "^";

            diag += ui->cbb_tr_symptom2->currentText() + "^";
            diag += getNatCode(ui->cbb_tr_symptom2->currentText(), "9");

            all_diags << diag;
        }
        else
        {

            diag += ui->cbb_tr_diag2->currentText() + "^";
            diag += getNatCode(ui->cbb_tr_diag2->currentText(), "8") + "^";

            diag += ui->cbb_tr_symptom2->currentText() + "^";
            diag += getNatCode(ui->cbb_tr_symptom2->currentText(), "9");

            all_diags[idx] = diag;

        }
    }

    if(!ui->cbbDiag3->currentText().isEmpty())
    {
        diag = ui->cbbDiag3->currentText() + "^";
        diag += getNatCode(ui->cbbDiag3->currentText(), "2") + "^";

        int idx = key_diags.indexOf(diag);

        if( idx < 0)
        {
            key_diags << diag;

            diag += ui->cbb_tr_diag3->currentText() + "^";
            diag += getNatCode(ui->cbb_tr_diag3->currentText(), "8") + "^";

            diag += ui->cbb_tr_symptom3->currentText() + "^";
            diag += getNatCode(ui->cbb_tr_symptom3->currentText(), "9");

            all_diags << diag;
        }
        else
        {
            diag += ui->cbb_tr_diag3->currentText() + "^";
            diag += getNatCode(ui->cbb_tr_diag3->currentText(), "8") + "^";

            diag += ui->cbb_tr_symptom3->currentText() + "^";
            diag += getNatCode(ui->cbb_tr_symptom3->currentText(), "9");

            all_diags[idx] = diag;

        }
    }

    qDebug()<<"全部诊断 : "<<all_diags;

    initialFinished = false;

    restore_diag_comb("111");

    //整理之后的诊断

    if(all_diags.size()>0)
    {
        diag = all_diags[0];
        ui->cbbDiag1->setCurrentText(pub::getStr(diag, "^", 1));
        ui->le_diag1->setText(pub::getStr(diag, "^", 1));
        ui->cbb_tr_diag1->setCurrentText(pub::getStr(diag, "^", 3));
        ui->cbb_tr_symptom1->setCurrentText(pub::getStr(diag, "^", 5));

        //预置
        ui->le_diag2->setText("");
        ui->le_diag3->setText("");
    }

    if(all_diags.size()>1)
    {
        diag = all_diags[1];
        ui->cbbDiag2->setCurrentText(pub::getStr(diag, "^", 1));
        ui->le_diag2->setText(pub::getStr(diag, "^", 1));
        ui->cbb_tr_diag2->setCurrentText(pub::getStr(diag, "^", 3));
        ui->cbb_tr_symptom2->setCurrentText(pub::getStr(diag, "^", 5));

        //预置
        ui->le_diag3->setText("");
    }

    if(all_diags.size()>2)
    {
        diag = all_diags[2];
        ui->cbbDiag3->setCurrentText(pub::getStr(diag, "^", 1));
        ui->le_diag3->setText(pub::getStr(diag, "^", 1));
        ui->cbb_tr_diag3->setCurrentText(pub::getStr(diag, "^", 3));
        ui->cbb_tr_symptom3->setCurrentText(pub::getStr(diag, "^", 5));
    }

    initialFinished = true;

}

void Form_ys_bzgl::restore_diag_comb(QString mode)
{
    //恢复诊断列表, mode 3 位， 分别指示哪一列需要恢复. 111 全恢复，000 全不恢复
    //initialFinished 状态由调用模块维护

    QString sq_diag,sq_diag_tr,sq_symp_tr;
    sq_diag = "select item_name from com_dict_icpc where instr(dept_code, '"
            + pub::dp_code + "') > 0 and type = '2' order by convert(item_name using gbk)";

    sq_diag_tr = "select item_name from com_dict_icpc where instr(dept_code, '"
            + pub::dp_code + "') > 0 and type = '8' order by convert(item_name using gbk)";

    sq_symp_tr = "select item_name from com_dict_icpc where instr(dept_code, '"
            + pub::dp_code + "') > 0 and type = '9' order by convert(item_name using gbk)";

    if(mode.mid(0,1) == "1")
    {
        fillCombo(ui->cbbDiag1, sq_diag, -1);   //主诊断
        fillCombo(ui->cbb_tr_diag1, sq_diag_tr, -1);   //中医主诊断
        fillCombo(ui->cbb_tr_symptom1, sq_symp_tr, -1);   //中医证候1
    }

    if(mode.mid(1,1) == "1")
    {
        fillCombo(ui->cbbDiag2, sq_diag, -1);   //诊断2
        fillCombo(ui->cbb_tr_diag2, sq_diag_tr, -1);   //中医诊断2
        fillCombo(ui->cbb_tr_symptom2, sq_symp_tr, -1);   //中医证候2
    }

    if(mode.mid(2,1) == "1")
    {
        fillCombo(ui->cbbDiag3, sq_diag, -1);   //诊断3
        fillCombo(ui->cbb_tr_diag3, sq_diag_tr, -1);   //中医诊断3
        fillCombo(ui->cbb_tr_symptom3, sq_symp_tr, -1);   //中医证候3
    }


}

void Form_ys_bzgl::on_cbb_yz_currentTextChanged(const QString &arg1)
{
    qDebug()<<"on_cbb_yz_currentTextChanged: "<<arg1<<"\n";
    if(!initialFinished)    return; //界面初始化未完成

    QString text = arg1.trimmed();

    if(ui->cbb_yz->currentIndex() == 0)  return;

    text = doct_ord[text]; //转换成完整内容

    ui->pt_medical_advice->insertPlainText(text + "；");

    ui->cbb_yz->setCurrentIndex(0);
}

void Form_ys_bzgl::change_camera(QString cam_name)
{

    qDebug()<<"change camera \n";
    
    QSettings setIni("clin.ini", QSettings::IniFormat);

    int camera_mode = setIni.value("camera/"+cam_name+"/defaultMode").toInt();

    ui->imageList->setViewMode(QListView::IconMode);    //设置QListWidget的显示模式
    ui->imageList->setIconSize(QSize(200,150));//设置QListWidget中单元项的图片大小
    ui->imageList->setSpacing(10);//设置QListWidget中单元项的间距
    ui->imageList->setResizeMode(QListWidget::Adjust);//设置自动适应布局调整（Adjust适应，Fixed不适应），默认不适应
    ui->imageList->setMovement(QListWidget::Static);//设置不能移动

    QString cam_device_name;

    for(int i = 0; i < cameraList.size(); i++)
    {
        //ui->cbb_cam_id->addItem(QString::number(i-1));
        if(cameraList[i].description() == cam_name)
        {
            cam_device_name = cameraList[i].deviceName();
        }
    }


    if(cam_device_name.isEmpty())
    {
        QMessageBox::warning(this, "Note", "摄像头设备名称无效！");
    }

    camera=new QCamera(cam_device_name.toLatin1());//摄像头 .data()
    viewfinder=new QCameraViewfinder(this);//取景器
    ui->layout_capture->addWidget(viewfinder);
    camera->setViewfinder(viewfinder);
    camera->setCaptureMode(QCamera::CaptureStillImage);
    imageCapture=new QCameraImageCapture(camera);
    imageCapture->setCaptureDestination(QCameraImageCapture::CaptureToFile);

    camera->start(); //启动摄像头

    connect(imageCapture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(cameraImageCaptured(int,QImage)));

    //获取摄像头支持的分辨率、帧率等参数
    QList<QCameraViewfinderSettings > ViewSets = camera->supportedViewfinderSettings();

    //设置摄像头参数
    if(ViewSets.count() >0)
    {
        if(ViewSets.count() > camera_mode)
        {
            QCameraViewfinderSettings vfs;
            double r ;
            vfs.setResolution(ViewSets[camera_mode].resolution());
            vfs.setPixelFormat(ViewSets[camera_mode].pixelFormat());
            r = ViewSets[camera_mode].maximumFrameRate();

            if(! qIsInf(r))
            {
                vfs.setMaximumFrameRate(r);
            }

            r = ViewSets[camera_mode].minimumFrameRate();

            if(! qIsInf(r))
            {
                vfs.setMinimumFrameRate(r);
            }

            vfs.setPixelAspectRatio(ViewSets[camera_mode].pixelAspectRatio());
            camera->setViewfinderSettings(vfs);
        }
        else
        {
            QMessageBox::information(this,"","摄像头参数无效，请重新设置！");
        }

    }
    else
    {
        QMessageBox::information(this,"","摄像头无可用启动参数 ！");
        camera->stop();
        camera->unload();
        delete camera;
        camera = nullptr;
    }
}

void Form_ys_bzgl::camera_initial()
{

    qDebug()<<"will initial camera preview\n";

    if(mpPatientInfo["clinic_code"].isEmpty())
    {
        ui->tab_image->setEnabled(false);
        return ;
    }

    dlgDelay->setText("正在初始化摄像头。。。");
    dlgDelay->setModal(true);
    dlgDelay->setNeedClose(false);
    dlgDelay->show();
    qApp->processEvents();

    //提取设备列表
    cameraList = QCameraInfo::availableCameras();

    if( 0 == cameraList.size())
    {
        qDebug()<<"has no camera.\n";
        has_camera = false;
        ui->tab_image->setEnabled(false);
        ui->cbb_cam_id->clear();

        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();

        return;
    }
    else
    {
        has_camera = true;
        ui->tab_image->setEnabled(true);
    }

    if(camera != nullptr)
    {
        camera->stop();
        camera->unload();
        delete camera;
        camera = nullptr;
    }

    if(viewfinder != nullptr)
    {
        delete viewfinder;
        viewfinder = nullptr;
    }

    if(imageCapture != nullptr)
    {
        delete imageCapture;
        imageCapture = nullptr;
    }

    QSettings setIni("clin.ini", QSettings::IniFormat);

    QString cur_cam_name = setIni.value("camera/defaultCamera").toString();
    int cur_cam_sn = setIni.value("camera/defaultId").toInt();
    int camera_mode = setIni.value("camera/"+cur_cam_name+"/defaultMode").toInt();

    for(int i = 0; i < cameraList.size(); i++)
    {
        //ui->cbb_cam_id->addItem(QString::number(i-1));
        ui->cbb_cam_id->addItem(cameraList[i].description());
    }

    ui->cbb_cam_id->setCurrentText(cur_cam_name);

    if( ui->cbb_cam_id->currentText().isEmpty())
    {
        //默认摄像头不在列表中，启用列表中的第一个摄像头
        cur_cam_name = cameraList[0].description();
        camera_mode = setIni.value("camera/"+cur_cam_name+"/defaultMode").toInt();
    }

    ui->imageList->setViewMode(QListView::IconMode);    //设置QListWidget的显示模式
    ui->imageList->setIconSize(QSize(200,150));//设置QListWidget中单元项的图片大小
    ui->imageList->setSpacing(10);//设置QListWidget中单元项的间距
    ui->imageList->setResizeMode(QListWidget::Adjust);//设置自动适应布局调整（Adjust适应，Fixed不适应），默认不适应
    ui->imageList->setMovement(QListWidget::Static);//设置不能移动

    QString cam_device_name;

    cur_cam_name=ui->cbb_cam_id->currentText();

    for(int i = 0; i < cameraList.size(); i++)
    {
        //ui->cbb_cam_id->addItem(QString::number(i-1));
        if(cameraList[i].description() == cur_cam_name)
        {
            cam_device_name = cameraList[i].deviceName();
        }
    }


    if(cam_device_name.isEmpty())
    {
        QMessageBox::warning(this, "Note", "摄像头设备名称无效！");
    }

    if(camera == nullptr)
    {
        camera=new QCamera(cam_device_name.toLatin1());//摄像头 .data()
    }

    if(viewfinder == nullptr)
    {
        viewfinder=new QCameraViewfinder(this);//取景器
    }

    ui->layout_capture->addWidget(viewfinder);
    camera->setViewfinder(viewfinder);
    camera->setCaptureMode(QCamera::CaptureStillImage);
    if(imageCapture == nullptr)
    {
        imageCapture=new QCameraImageCapture(camera);
    }

    imageCapture->setCaptureDestination(QCameraImageCapture::CaptureToFile);

    camera->start(); //启动摄像头

    qDebug()<<"start camera. \n";

    connect(imageCapture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(cameraImageCaptured(int,QImage)));

    //获取摄像头支持的分辨率、帧率等参数
    QList<QCameraViewfinderSettings > ViewSets = camera->supportedViewfinderSettings();

    //设置摄像头参数
    bool finish = true;
    if(ViewSets.count() >0)
    {
        if(ViewSets.count() > camera_mode)
        {
            QCameraViewfinderSettings vfs;
            double r ;
            vfs.setResolution(ViewSets[camera_mode].resolution());
            vfs.setPixelFormat(ViewSets[camera_mode].pixelFormat());
            r = ViewSets[camera_mode].maximumFrameRate();

            if(! qIsInf(r))
            {
                vfs.setMaximumFrameRate(r);
            }

            r = ViewSets[camera_mode].minimumFrameRate();

            if(! qIsInf(r))
            {
                vfs.setMinimumFrameRate(r);
            }

            vfs.setPixelAspectRatio(ViewSets[camera_mode].pixelAspectRatio());
            camera->setViewfinderSettings(vfs);
        }
        else
        {
            QMessageBox::information(this,"","摄像头参数无效，请重新设置！");

            finish = false;
        }

    }
    else
    {
        QMessageBox::information(this,"","摄像头无可用启动参数 ！");

        finish = false;
    }

    if(!finish)
    {
        camera->stop();
        camera->unload();
        delete camera;
        camera = nullptr;
        camera_initialized = false;
    }
    else
    {
        camera_initialized = true;
    }

    dlgDelay->setNeedClose(true);
    dlgDelay->closeWindow();

}

void Form_ys_bzgl::cameraImageCaptured(int, QImage image)
{
    qDebug()<<"cameraImageCaptured\n";
    //search valid filename
    QString fileName ,fName;
    while(true)
    {
        pic_num ++;
        fileName = pic_path + "/" + QString::number(pic_num)+".jpg";

        if (!QFile::exists(fileName))
        {
            break;
        }
    }

    image.save(fileName);
    pic_describe[QString::number(pic_num)] = ui->le_pic_describe->text().trimmed();

    //定义QListWidgetItem对象
    QListWidgetItem *imageItem = new QListWidgetItem;
    //为单元项设置属性
    imageItem->setIcon(QIcon(fileName));
    QFont ft = QFont();
    ft.setPointSize(10);
    imageItem->setFont(ft);
    imageItem->setText(fileName);
    //重新设置单元项图片的宽度和高度
    imageItem->setSizeHint(QSize(200,150));
    //将单元项添加到QListWidget中
    ui->imageList->addItem(imageItem);

    //ui->pbDelete->setEnabled(true);

}

void Form_ys_bzgl::on_pb_cap_take_clicked()
{
    if(mpPatientInfo["clinic_code"].isEmpty())
    {
        QMessageBox::information(this, "注意", "患者信息无效！");
        return ;
    }
    imageCapture->capture();
}

void Form_ys_bzgl::on_pb_cap_setup_clicked()
{
    if(cap_setup == NULL)
    {
        cap_setup = new Ys_cap_setup();//摄像头设置
    }

    camera->stop();
    camera->unload();
    delete camera;
    camera = nullptr;

    cap_setup->exec();

    camera_initial();
    //change_camera(ui->cbb_cam_id->currentText());
}

void Form_ys_bzgl::on_cbb_cam_id_currentTextChanged(const QString &arg1)
{
    if(!camera_initialized)
    {
        return;
    }
    qDebug()<<"camera changed.\n";

    if(camera != nullptr)
    {
        camera->stop();
        camera->unload();
        delete camera;
        camera = nullptr;
    }

    if(viewfinder != nullptr)
    {
        delete viewfinder;
        viewfinder = nullptr;
    }

    if(imageCapture != nullptr)
    {
        delete imageCapture;
        imageCapture = nullptr;
    }

    change_camera(arg1);
}

void Form_ys_bzgl::on_pb_cap_remove_clicked()
{
    if( -1 == ui->imageList->currentRow() )
    {
        QMessageBox::about(this,"提示","请先选中要删除的图片！");
        return;
    }

    QString tmpFile = ui->imageList->currentItem()->text();

    QDir *destFile = new QDir;
    bool exist = destFile->exists(tmpFile);

    if (exist)
    {
        destFile->remove(tmpFile);
        delete ui->imageList->currentItem();
    }

    if( -1 == ui->imageList->currentRow() )
    {
    //    ui->pbDelete->setEnabled(false);
    }

}

void Form_ys_bzgl::on_pb_pic_save_clicked()
{

    qDebug()<<"on_pb_pic_save_clicked()\n";

    QDir d = QDir(pic_path);
    d.setNameFilters( QStringList("*.jpg") );
    QStringList files = d.entryList();  //read filenames

    if(files.size() < 1)
    {
        qDebug()<<"no image file found.\n";
        if(ui->tabWidget->currentIndex() == 5)
        {
            QMessageBox::warning(this, "Note", "无有效图像文件！");
            ui->imageList->clear();
        }
        return;
    }

    QString reg_dt = mpPatientInfo["date"];
    QString card_no = mpPatientInfo["card_no"];
    QString clinic_code = mpPatientInfo["clinic_code"];
    QString p_name = mpPatientInfo["name"];
    QString dest_path = pic_path+"/"+card_no;
    QDir dest_d = QDir();

    if(!dest_d.exists(dest_path))
    {
        dest_d.mkdir(dest_path);
    }

    QString pic_sq, tm_mark, dest_filename;

    for(int i = 0; i < files.size() ; i++)
    {
        QFile f(pic_path + "/" + files[i]);

        QFileInfo f_inf(f);
        QString baseName = f_inf.baseName();    //为提取图像文件描述
        QString pic_desc = pic_describe[baseName];

        //tm_mark = qrmt->value(0).toString();
        tm_mark = QDateTime::currentDateTime().toString("yyyyMMddHHmmsszzz");

        dest_filename = card_no + "-" + tm_mark + ".jpg";

        f.copy(dest_path + "/" + dest_filename);

        QString sync_flag = "0";

        if(remote_file_syncronize(dest_path, dest_filename))
        {
            sync_flag = "1";
        }

        pic_sq = "insert into ys_bz_e_pic "
                 "(oper_date, card_no, pic_name, "
                 "doc_name, doc_code, pic_describe, clinic_code, "
                 "patient_name, reg_date, tm_mark, sync_flag) "
                 "values"
                 "(curdate(), '%1', '%2', "     //card_no, dest_filename
                 "'%3', '%4', '%5', '%6', " //doc_name,doc_code, file_describe, clinic_code
                 "'%7', '%8', '%9','%10')";//patietn_name, reg_date, tm_mark

        pic_sq = pic_sq.arg(card_no)
                .arg(dest_filename)
                .arg(pub::usr_name)
                .arg(pub::usr_code)
                .arg(pic_desc)
                .arg(clinic_code)
                .arg(p_name)
                .arg(reg_dt)
                .arg(tm_mark)
                .arg(sync_flag);

        qDebug()<<"保存图像记录信息\n"<<pic_sq;

        if(!qrmt->exec(pic_sq))
        {
            QMessageBox::warning(this, "Note", "图像信息保存失败！");
            return;
        }

        f.remove();
    }

    if(ui->tabWidget->currentIndex() == 5)
    {
        QMessageBox::warning(this, "Note", "图像信息已保存！");
        ui->imageList->clear();
    }

}

bool Form_ys_bzgl::remote_file_syncronize(QString file_path, QString file_name)
{
    qDebug()<<"remote_file_syncronize\n";

    QDir dest_d = QDir();
    QFile fl;

    QString dest_path = remote_path + "/" + mpPatientInfo["card_no"];

    if(!dest_d.exists(dest_path))
    {
        dest_d.mkdir(dest_path);
    }


    QString remote_name = dest_path + "/" + file_name;

    QString sour = file_path + "/" + file_name;
    QString dest = dest_path + "/" + file_name;
qDebug()<<"source : "<<sour;
qDebug()<<"destination : "<<dest;
    if(fl.copy(sour, dest))
    {
        return true;
    }
    else
    {
        return false;
    }

}

void Form_ys_bzgl::on_pb_pic_refresh_clicked()
{
    qDebug()<<"on_pb_pic_refresh_clicked\n";
    if(mpPatientInfo["clinic_code"].isEmpty())
    {
        QMessageBox::information(this, "注意", "患者信息无效！");
        return ;
    }

    sq = "select oper_date 操作日期, pic_describe 内容 , sync_flag ," //0-2
         " card_no, pic_name, doc_code, doc_name, clinic_code,tm_mark" //3-8
         " from ys_bz_e_pic "
         " where card_no = '%1'"
         " order by atinc";
    sq = sq.arg(mpPatientInfo["card_no"]);

    qDebug()<<"display image describe:\n"<<sq;

    md_pics->setQuery(sq, pub::db_m);
    ui->tv_pic_display->setModel(md_pics);
    int w = ui->tv_pic_display->width();
    pub::setColumnWidth(ui->tv_pic_display, "0.45^0.4^0^0^0^0^0^0^0", w);

    ui->pb_pic_describe_change->setEnabled(false);
}

void Form_ys_bzgl::on_tv_pic_display_doubleClicked(const QModelIndex &index)
{
    on_tv_pic_display_clicked(index);
}

void Form_ys_bzgl::on_tv_pic_display_clicked(const QModelIndex &index)
{
    qDebug()<<"on_tv_pic_display_clicked\n";
    QString pic_desc = index.siblingAtColumn(1).data().toString();
    QString sync_flag = index.siblingAtColumn(2).data().toString();
    QString card_no = index.siblingAtColumn(3).data().toString();
    QString pic_name = index.siblingAtColumn(4).data().toString();
    QString doc_code = index.siblingAtColumn(5).data().toString();
    QString doc_name = index.siblingAtColumn(6).data().toString();

    ui->le_pic_desc->setText(pic_desc);

    QString local_flnm = pic_path + "/" + card_no + "/" + pic_name;
    QString remote_flnm = remote_path + "/" + card_no + "/" + pic_name;

    qDebug()<<"local, remote : "<<local_flnm<<","<< remote_flnm;

    bool local_exist = QFile::exists(local_flnm);
    bool remote_exist = QFile::exists(remote_flnm);

    if(!local_exist && !remote_exist)
    {
        qDebug()<<"本地远程均无文件\n";
        QMessageBox::information(this, "注意", "本地和远程均找不到文件，请联系存有此文件的同事重新上传。");
        return;
    }

    if(local_exist && !remote_exist)
    {
        qDebug()<<"本地有，远程无，由本地向同步远程\n";
        QDir dest_d = QDir();
        QString dest_path = remote_path + "/" + card_no;

        if(!dest_d.exists(dest_path))
        {
            dest_d.mkdir(dest_path);
        }

        if(!QFile::copy(local_flnm, remote_flnm))
        {
            qDebug()<<"文件复制失败\n";
        }
    }

    if(!local_exist && remote_exist)
    {
        qDebug()<<"本地无，远程有，由远程向同步本地\n";
        QDir dest_d = QDir();
        QString dest_path = pic_path + "/" + card_no;

        if(!dest_d.exists(dest_path))
        {
            dest_d.mkdir(dest_path);
        }

        if(!QFile::copy(remote_flnm, local_flnm))
        {
            qDebug()<<"文件复制失败\n";
        }

    }


    //显示本地图像
    local_exist = QFile::exists(local_flnm);

    if(!local_exist)
    {
        qDebug()<<"本地文件无效\n";
        QMessageBox::information(this, "注意", "本地文件无效！");
        return;
    }

    qDebug()<<"file name is : "<<local_flnm<<"\n";

    //QImage image(flnm);

    QPixmap pixmap(local_flnm);

    scene->clear();
    pixmapItem = scene->addPixmap(pixmap);
    view->setAlignment(Qt::AlignCenter); // 设置内容居中
    pic_scale_factor = 1;
    scene->setSceneRect(pixmap.rect()); // 设置场景矩形为图像大小
    pic_fitToView();// 自动缩放到合适大小

    if(pub::usr_code == doc_code)
    {
        ui->pb_pic_describe_change->setEnabled(true);
    }
    else
    {
        ui->pb_pic_describe_change->setEnabled(false);
    }

}

void Form_ys_bzgl::pic_fitToView()
{
    if (!pixmapItem) return;

    // 获取视图和图像尺寸
    QSize viewSize = view->size();
    QSize imageSize = pixmapItem->pixmap().size();

    // 计算合适的缩放比例
    double widthRatio = static_cast<double>(viewSize.width()) / imageSize.width();
    double heightRatio = static_cast<double>(viewSize.height()) / imageSize.height();
    double fitFactor = qMin(widthRatio, heightRatio);

    // 应用缩放
    pic_scale_factor = fitFactor;
    view->resetTransform();
    view->scale(pic_scale_factor, pic_scale_factor);
}

void Form_ys_bzgl::pic_zoomIn()
{
    pic_scale_factor *= 0.8;
    view->setTransform(QTransform::fromScale(pic_scale_factor, pic_scale_factor));
}

void Form_ys_bzgl::pic_zoomOut()
{
    pic_scale_factor *= 1.2;
    view->setTransform(QTransform::fromScale(pic_scale_factor, pic_scale_factor));
}

void Form_ys_bzgl::on_pb_pic_upload_clicked()
{

    qDebug()<<"on_pb_pic_upload_clicked\n";

    if(!ui->tv_pic_display->currentIndex().isValid())
    {
        QMessageBox::information(this, "注意", "未选定有效图像信息！");
        return;
    }

    QString card_no = ui->tv_pic_display->currentIndex().siblingAtColumn(3).data().toString();
    QString pic_name = ui->tv_pic_display->currentIndex().siblingAtColumn(4).data().toString();


    QString local_flnm = pic_path + "/" + card_no + "/" + pic_name;
    QString remote_flnm = remote_path + "/" + card_no + "/" + pic_name;

    bool local_exist = QFile::exists(local_flnm);
    bool remote_exist = QFile::exists(remote_flnm);

    if(remote_exist)
    {
        QMessageBox::information(this, "注意", "远程文件已经存在！");
        return;
    }

    if(!local_exist)
    {
        QMessageBox::information(this, "注意", "本地文件不存在，无法进行同步操作。");
        return;
    }

    //本地有，远程无，由本地向同步远程
    QDir dest_d = QDir();
    QString dest_path = remote_path + "/" + card_no;

    if(!dest_d.exists(dest_path))
    {
        dest_d.mkdir(dest_path);
    }

    if(QFile::copy(local_flnm, remote_flnm))
    {
        QMessageBox::information(this, "注意", "文件同步操作成功！");
    }
    else
    {
        QMessageBox::information(this, "注意", "文件同步操作失败！");
    }

}

void Form_ys_bzgl::on_pb_pic_describe_change_clicked()
{

    qDebug()<<"on_pb_pic_describe_change_clicked\n";

    if(!ui->tv_pic_display->currentIndex().isValid())
    {
        QMessageBox::information(this, "注意", "未选定有效图像信息！");
        return;
    }

    QString card_no = ui->tv_pic_display->currentIndex().siblingAtColumn(3).data().toString();
    QString tm_mark = ui->tv_pic_display->currentIndex().siblingAtColumn(8).data().toString();

    sq = "update ys_bz_e_pic set pic_describe = '%1'"
         " where card_no = '%2' and tm_mark = '%3'";

    sq = sq.arg(ui->le_pic_desc->text().trimmed())
            .arg(card_no)
            .arg(tm_mark);
    qDebug()<<"change pic_describe. \n";

    qrmt->exec(sq);

    on_pb_pic_refresh_clicked();
}

bool Form_ys_bzgl::push_5465(QString ord_id)
{
    qDebug()<<"Form_ys_bzgl::push_5465()\n";

    // 构建JSON请求体
    QJsonObject json;

    QJsonObject json_sub,json_sub_sub;

    json_sub_sub["outBizType"] = "HOSPITAL_PAYMENT";
    json_sub_sub["orderStatus"] = "MERCHANT_WAIT_PAY";
    json_sub["aliExtData"] = json_sub_sub;

    json_sub["pushType"] = "ZHYB_APP";
    json_sub["orgCodg"] = pub::hos_ybbh;
    json_sub["hisAreaCody"] = pub::dp_code;
    json_sub["medOrgOrd"] = ord_id; //mpPatientInfo["medOrgOrd"]
    json_sub["psnCertType"] = "01";
    json_sub["certno"] = mpPatientInfo["idenno"];
    json_sub["psnName"] = mpPatientInfo["name"];

    QString info_ret;
    QJsonObject js_ret;

    request_zjzf.setUrl(QUrl(pub::zj_push_ip + "/medinsOrd/pushMsg"));

    if(pub::call_busi_push("5465", json_sub, info_ret, js_ret, "" , true, manager, request_zjzf, mpPatientInfo["clinic_code"]))
    {
        qDebug()<<"pub::call_busi_push 5465 return : " << info_ret << "\n";
        return true;
    }
    else
    {
        qDebug()<<"pub::call_busi_push 5465 return : " << info_ret << "\n";
        return false;
    }

}

void Form_ys_bzgl::save_5465(QString mode)
{
    qDebug()<<"Form_ys_bzgl::save_5465()\n";

    //保存诊间支付消息, mode = 1,保存；mode = 0,撤销；
    if(mode == "1")
    {
        //保存处方之后调用
        qro->exec("select seq_fin_zjzf_msgid.nextval from dual");
        qro->next();

        QString medOrgOrd = qro->value(0).toString();

        mpPatientInfo["medOrgOrd"] = medOrgOrd;

        sq = "insert into zjzf_5465_push"
             " (push_time,push_oper_code, medorgord, clinic_code," //0-3
             " card_no, patient_name, patient_idenno, dept_code,"//4-7
             " push_state, mdtrt_id, setl_id,"//8-10
             " dept_name, doct_code, doct_name, dise_code,"//11-14
             " dept_code_st, reg_time, tot_cost, recipe_no) "//15-18
             " values(";
        //0-3
        sq += " now(), ";
        sq += "'" + pub::usr_code + "',";
        sq += "'" + medOrgOrd + "',";
        sq += "'" + mpPatientInfo["clinic_code"] + "',";
        //4-7
        sq += "'" + mpPatientInfo["card_no"] + "',";
        sq += "'" + mpPatientInfo["name"] + "',";
        sq += "'" + mpPatientInfo["idenno"] + "',";
        sq += "'" + pub::dp_code + "',";
        //8-10
        sq += "'0','','',";
        //11-14
        sq += "'" + pub::dp_name + "',";
        sq += "'" + pub::dr_codg + "',";
        sq += "'" + pub::usr_name + "',";
        sq += "'" + getNatCode(ui->cbbDiag1->currentText(), "2") + "',";
        //15-17
        sq += "'" + pub::dp_code_st + "',";
        sq += "'" + mpPatientInfo["reg_date"] + "',";
        sq += "'" + ui->leAmount->text() + "',";
        sq += "'" + recipe_list_5465.join("^") + "'";

        sq += ") ";

        qDebug()<<"写入push_5465:"<<sq<<"\n";
        qrm->exec(sq);
    }
    else
    {
        //处方召回或项目撤销之后调用
        foreach(QString rcp, recipe_list_5465)
        {
            sq = " update zjzf_5465_push set "
                 " push_state = '1',"
                 " end_time = now(),"
                 " end_oper_code = '%3' "
                 " where clinic_code = '%1'"
                 " and push_state = '0' and recipe_no like '%%2%'";
            sq = sq.arg(mpPatientInfo["clinic_code"]).arg(rcp).arg(pub::usr_code);

            qDebug()<<"写入push_5465:"<<sq<<"\n";
            qrm->exec(sq);
        }
        //
    }

}

QString Form_ys_bzgl::cur_sm3(QString mode, QString plan)
{

    qDebug()<<"QString Form_ys_bzgl::cur_sm3(QString mode, QString plan)\n";
    //保存病志，mode为screen，计算屏幕内容 + 已经保存过的诊疗计划
    //更新诊疗计划，mode为database，计算数据库内容 + 参数传入的新诊疗计划

    QString calc;//参与计算校验码的字串
    //就诊原因//患者主诉//现病史//既往史//过敏史//个人史//月经史//家族史//体格检查
    //医嘱//中医查体//中医辩证依据//中医类证鉴别//中医治则//西医诊断//中医诊断

    if(mode == "screen")
    {
        qDebug()<<"录入病志，从屏幕提取基础信息\n";
        calc += ui->cbbReason->currentText();
        calc += ui->leHzzs->text();
        calc += ui->pt_current_symp->toPlainText();
        calc += ui->leJws->text();
        calc += ui->leGms->text();
        calc += ui->pt_person_history->toPlainText();
        calc += ui->le_menstr->text();
        calc += ui->pt_family_history->toPlainText();
        calc += ui->pt_body_check->toPlainText();
        calc += ui->pt_medical_advice->toPlainText();
        calc += ui->pt_body_check_tr->toPlainText();
        calc += ui->pt_tr_diag->toPlainText();
        calc += ui->pt_similar_syndrom->toPlainText();
        calc += ui->pt_treat_tr->toPlainText();
        calc += ui->cbbDiag1->currentText();

        if(!ui->cbbDiag2->currentText().isEmpty())
        {
            calc += "^" + ui->cbbDiag2->currentText();
        }

        if(!ui->cbbDiag3->currentText().isEmpty())
        {
            calc += "^" + ui->cbbDiag3->currentText();
        }

        calc += ui->cbb_tr_diag1->currentText() +
                "/" + ui->cbb_tr_symptom1->currentText();

        if((ui->cbb_tr_diag2->currentText() +
            "/"+ ui->cbb_tr_symptom2->currentText()) != "/")
        {
            calc += "^" + ui->cbb_tr_diag2->currentText() +
                    "/"+ ui->cbb_tr_symptom2->currentText();
        }

        if((ui->cbb_tr_diag3->currentText() +
            "/"+ ui->cbb_tr_symptom2->currentText()) != "/")
        {
            calc += "^" + ui->cbb_tr_diag3->currentText() +
                    "/"+ ui->cbb_tr_symptom2->currentText();
        }

        //从数据库提取诊疗计划
        sq = " select medical_plan from ys_bz_e_rec "
             " where clinic_code = '%1' ";
        sq = sq.arg(mpPatientInfo["clinic_code"]);
        qDebug()<<"提取已保存过的诊疗计划 \n";
        qrmt->exec(sq);

        if(qrmt->next())
        {
            //存在,加入本次计算字串
            calc += qrmt->value(0).toString();
        }
    }
    else
    {
        //从数据库提取基础病志内容
        sq = " select * from ys_bz_e_rec where clinic_code = '%1' ";
        sq = sq.arg(mpPatientInfo["clinic_code"]);
        qDebug()<<"变更诊疗计划，从数据库提取基础病志内容"<<sq<<" \n";
        qrm->exec(sq);
        if(!qrm->next())
        {
            qDebug()<<"未找到基础病志内容 \n";
            return "";
        }

        calc += qrm->value("jzyy").toString();
        calc += qrm->value("hzzs").toString();
        calc += qrm->value("xbs").toString();
        calc += qrm->value("jws").toString();
        calc += qrm->value("gms").toString();
        calc += qrm->value("person_hist").toString();
        calc += qrm->value("menstr_hist").toString();
        calc += qrm->value("family_hist").toString();
        calc += qrm->value("tgjc").toString();
        calc += qrm->value("yz").toString();

        //西医诊断
        calc += qrm->value("zd1").toString();

        if(!qrm->value("zd2").toString().isEmpty())
        {
            calc += "^" + qrm->value("zd2").toString();
        }

        if(!qrm->value("zd3").toString().isEmpty())
        {
            calc += "^" + qrm->value("zd3").toString();
        }

        //中医诊断
        calc += qrm->value("zyzd1").toString() + "/" + qrm->value("zyzh1").toString();

        if(qrm->value("zyzd2").toString() + "/" + qrm->value("zyzh2").toString() != "/")
        {
            calc += "^" + qrm->value("zyzd2").toString() + "/" + qrm->value("zyzh2").toString();
        }

        if(qrm->value("zyzd3").toString() + "/" + qrm->value("zyzh3").toString() != "/")
        {
            calc += "^" + qrm->value("zyzd3").toString() + "/" + qrm->value("zyzh3").toString();
        }

        calc += qrm->value("tgjc_tr").toString();
        calc += qrm->value("zybz").toString();
        calc += qrm->value("similar_syndrom").toString();
        calc += qrm->value("treat_tr").toString();

        calc += plan;

    }

    //计算 sm3 code
    QString calc_sm3 = pub::gmssl_sm3(pub::hos_ybbh + calc + pub::usr_code).trimmed();
    qDebug()<<"calc , sm3 : "<<calc<<"\n"<<calc_sm3<<"\n";

    return calc_sm3;

}

bool Form_ys_bzgl::med_rec()
{

    qDebug()<<"bool Form_ys_bzgl::med_rec()\n";

    //时间戳
    QString tmstmp = QString::number(QDateTime::currentDateTime().toMSecsSinceEpoch());
    QString calc_sm3 = cur_sm3("screen");

    int change_status = 0; //病志内容是否有变化

    sq = "select * from ys_bz_e_rec where clinic_code = '" + mpPatientInfo["clinic_code"] + "' ";
    qDebug()<<"检索病志是否存在："<<sq<<"\n";
    qrm->exec(sq);

    if(!qrm->next())//记录不存在，插入新记录
    {
        change_status = 1;//标记，需要进行 sm3 保存

        sq = "insert into ys_bz_e_rec ("
             "tmstmp,sm3,zljl, clinic_code, card_no, dept_code, doct_code," //-2,0-4
                "rq, zs, hzzs, xbs, person_hist, menstr_hist,"//5-10
                "family_hist, jws, gms, yz, tgjc, cbzd, ys,"//11-17
                "jzyy, jzyyc, reg_date, diag_date, rlts,"//18-22
                "trustee_name, trustee_tel, trustee_certno,"//23-25
                "zd1,zd2,zd3,zd1c,zd2c,zd3c";//26-31 西医诊断

        //中医相关
        if(!ui->rb_mode_med->isChecked())
        {
            sq += ",similar_syndrom, treat_tr, tgjc_tr,"//32-34
                    "zyzd1,zyzd2,zyzd3,zyzd1c,zyzd2c,zyzd3c,"//35-40 中医诊断
                    "zyzh1,zyzh2,zyzh3,zyzh1c,zyzh2c,zyzh3c,zybz"//41-47 中医证候
                    ;//
        }

        sq += " )values(";
        //-2,0-4
        sq += "now(),'" + calc_sm3 + "','";
        sq += ui->cbb_conclusion->currentText() + "','";//诊疗结论
        sq += mpPatientInfo["clinic_code"] + "','";
        sq += mpPatientInfo["card_no"] + "','";
        sq += pub::dp_code + "','" + pub::usr_code + "',";
        //5-10
        sq += " curdate(),'','";//诊室代码，用户代码，日期，诊室
        sq += ui->leHzzs->text().trimmed() + "','";//主诉
        sq += ui->pt_current_symp->toPlainText().trimmed() + "','";//现病史
        sq += ui->pt_person_history->toPlainText().trimmed() + "','";//个人史
        sq += ui->le_menstr->text().trimmed() + "','";//月经史
        //11-17
        sq += ui->pt_family_history->toPlainText().trimmed() + "','";//家族史
        sq += ui->leJws->text().trimmed() + "','";//既往史
        sq += ui->leGms->text().trimmed() + "','";//过敏史
        sq += ui->pt_medical_advice->toPlainText() + "','";//医嘱
        sq += ui->pt_body_check->toPlainText().trimmed() + "',";//体格检查
        sq += "'','" + pub::usr_name + "','";//初步诊断，医生姓名
        //18-22
        sq += ui->cbbReason->currentText() + "','";
        sq += getIcpcCode(ui->cbbReason->currentText()) + "','";
        sq += mpPatientInfo["reg_date"] + "',curtime(),'";
        sq += ui->cbbTrusteeRlt->currentText() + "','";
        //23-25
        sq += ui->leTrustee->text().trimmed() + "','";
        sq += ui->leTrusteeP->text().trimmed() + "','";
        sq += ui->leTrusteeI->text().trimmed() + "',";
        //26-31 西医诊断
        sq += "'" + ui->cbbDiag1->currentText() + "',";
        sq += "'" + ui->cbbDiag2->currentText() + "',";
        sq += "'" + ui->cbbDiag3->currentText() + "',";
        sq += "'" + getNatCode(ui->cbbDiag1->currentText(), "2") + "',";
        sq += "'" + getNatCode(ui->cbbDiag2->currentText(), "2") + "',";
        sq += "'" + getNatCode(ui->cbbDiag3->currentText(), "2") + "'";

        if(!ui->rb_mode_med->isChecked())
        {
            //中医相关
            //32-34
            sq += ",'" + ui->pt_similar_syndrom->toPlainText().trimmed() + "',";//类证
            sq += "'" + ui->pt_treat_tr->toPlainText().trimmed() + "',";//治则
            sq += "'" + ui->pt_body_check_tr->toPlainText().trimmed() +"',";//中医四诊
            //35-40 中医诊断
            sq += "'" + ui->cbb_tr_diag1->currentText() + "',";
            sq += "'" + ui->cbb_tr_diag2->currentText() + "',";
            sq += "'" + ui->cbb_tr_diag3->currentText() + "',";
            sq += "'" + getNatCode(ui->cbb_tr_diag1->currentText(), "8") + "',";
            sq += "'" + getNatCode(ui->cbb_tr_diag2->currentText(), "8") + "',";
            sq += "'" + getNatCode(ui->cbb_tr_diag3->currentText(), "8") + "',";
            //41-47 中医证候, 中医辩证
            sq += "'" + ui->cbb_tr_symptom1->currentText() + "',";
            sq += "'" + ui->cbb_tr_symptom2->currentText() + "',";
            sq += "'" + ui->cbb_tr_symptom3->currentText() + "',";
            sq += "'" + getNatCode(ui->cbb_tr_symptom1->currentText(), "9") + "',";
            sq += "'" + getNatCode(ui->cbb_tr_symptom2->currentText(), "9") + "',";
            sq += "'" + getNatCode(ui->cbb_tr_symptom3->currentText(), "9") + "',";
            sq += "'" + ui->pt_tr_diag->toPlainText() + "'";
        }
        sq += ")";

        qDebug()<<"保存新病志："<<sq;
        if(!qrm->exec(sq))
        {
            QMessageBox::information(this, "注意", "保存病志记录失败！\nerrmsg : " + qrm->lastError().text());
            qDebug()<<qrm->lastError().text();
            return false;
        }
    }
    else
    {
        //修改已经存在的记录。对旧数据进行备份
        qDebug()<<"update exists record.";

        QString atinc = qrm->value(0).toString();//保留 atinc 用于修改记录

        //就诊原因
        int ret = save_rec_hist("就诊原因", ui->cbbReason->currentText()
                                , qrm->value("jzyy").toString(),
                                tmstmp, mpPatientInfo["clinic_code"]);
        if(ret<0)
        {
            return false;
        }

        change_status += ret;

        //患者主诉
        ret = save_rec_hist("患者主诉", ui->leHzzs->text(),
                            qrm->value("hzzs").toString(),
                            tmstmp, mpPatientInfo["clinic_code"]);
        if(ret<0)
        {
            return false;
        }

        change_status += ret;

        //现病史
        ret = save_rec_hist("现病史", ui->pt_current_symp->toPlainText(),
                            qrm->value("xbs").toString(),
                            tmstmp, mpPatientInfo["clinic_code"]);
        if(ret<0)
        {
            return false;
        }

        change_status += ret;

        //既往史
        ret = save_rec_hist("既往史", ui->leJws->text(),
                            qrm->value("jws").toString(),
                            tmstmp, mpPatientInfo["clinic_code"]);
        if(ret<0)
        {
            return false;
        }

        change_status += ret;

        //过敏史
        ret = save_rec_hist("过敏史", ui->leGms->text(),
                            qrm->value("gms").toString(),
                            tmstmp, mpPatientInfo["clinic_code"]);
        if(ret<0)
        {
            return false;
        }

        change_status += ret;

        //个人史
        ret = save_rec_hist("个人史", ui->pt_person_history->toPlainText(),
                            qrm->value("person_hist").toString(),
                            tmstmp, mpPatientInfo["clinic_code"]);
        if(ret<0)
        {
            return false;
        }

        change_status += ret;

        //月经史
        ret = save_rec_hist("月经史", ui->le_menstr->text(),
                            qrm->value("menstr_hist").toString(),
                            tmstmp, mpPatientInfo["clinic_code"]);
        if(ret<0)
        {
            return false;
        }

        change_status += ret;

        //家族史
        ret = save_rec_hist("家族史", ui->pt_family_history->toPlainText(),
                            qrm->value("family_hist").toString(),
                            tmstmp, mpPatientInfo["clinic_code"]);
        if(ret<0)
        {
            return false;
        }

        change_status += ret;

        //体格检查
        ret = save_rec_hist("体格检查", ui->pt_body_check->toPlainText(),
                            qrm->value("tgjc").toString(),
                            tmstmp, mpPatientInfo["clinic_code"]);
        if(ret<0)
        {
            return false;
        }

        change_status += ret;

        //医嘱
        ret = save_rec_hist("医嘱", ui->pt_medical_advice->toPlainText(),
                            qrm->value("yz").toString(),
                            tmstmp, mpPatientInfo["clinic_code"]);
        if(ret<0)
        {
            return false;
        }

        change_status += ret;

        //西医诊断
        QString diag_new = ui->cbbDiag1->currentText();

        if(!ui->cbbDiag2->currentText().isEmpty())
        {
            diag_new += "^" + ui->cbbDiag2->currentText();
        }

        if(!ui->cbbDiag3->currentText().isEmpty())
        {
            diag_new += "^" + ui->cbbDiag3->currentText();
        }

        QString diag_old = qrm->value("zd1").toString();

        if(!qrm->value("zd2").toString().isEmpty())
        {
            diag_old += "^" + qrm->value("zd2").toString();
        }

        if(!qrm->value("zd3").toString().isEmpty())
        {
            diag_old += "^" + qrm->value("zd3").toString();
        }

        ret = save_rec_hist("西医诊断", diag_new, diag_old, tmstmp, mpPatientInfo["clinic_code"]);
        if(ret<0)
        {
            return false;
        }

        change_status += ret;

        //中医诊断
        diag_new = ui->cbb_tr_diag1->currentText() + "/" + ui->cbb_tr_symptom1->currentText();

        if(ui->cbb_tr_diag2->currentText() + "/"+ ui->cbb_tr_symptom2->currentText() != "/")
        {
            diag_new += "^" + ui->cbb_tr_diag2->currentText() + "/"+ ui->cbb_tr_symptom2->currentText();
        }

        if(ui->cbb_tr_diag3->currentText() + "/"+ ui->cbb_tr_symptom2->currentText() != "/")
        {
            diag_new += "^" + ui->cbb_tr_diag3->currentText() + "/"+ ui->cbb_tr_symptom2->currentText();
        }

        diag_old = qrm->value("zyzd1").toString() + "/" + qrm->value("zyzh1").toString();

        if(qrm->value("zyzd2").toString() + "/" + qrm->value("zyzh2").toString() != "/")
        {
            diag_old += "^" + qrm->value("zyzd2").toString() + "/" + qrm->value("zyzh2").toString();
        }

        if(qrm->value("zyzd3").toString() + "/" + qrm->value("zyzh3").toString() != "/")
        {
            diag_old += "^" + qrm->value("zyzd3").toString() + "/" + qrm->value("zyzh3").toString();
        }

        ret = save_rec_hist("中医诊断", diag_new, diag_old, tmstmp, mpPatientInfo["clinic_code"]);
        if(ret<0)
        {
            return false;
        }

        change_status += ret;

        //中医查体
        ret = save_rec_hist("中医查体", ui->pt_body_check_tr->toPlainText(),
                            qrm->value("tgjc_tr").toString(),
                            tmstmp, mpPatientInfo["clinic_code"]);
        if(ret<0)
        {
            return false;
        }

        change_status += ret;

        //中医辩证依据
        ret = save_rec_hist("中医辩证依据", ui->pt_tr_diag->toPlainText(),
                            qrm->value("zybz").toString(),
                            tmstmp, mpPatientInfo["clinic_code"]);
        if(ret<0)
        {
            return false;
        }

        change_status += ret;

        //中医类证鉴别
        ret = save_rec_hist("中医类证鉴别", ui->pt_similar_syndrom->toPlainText(),
                            qrm->value("similar_syndrom").toString(),
                            tmstmp, mpPatientInfo["clinic_code"]);
        if(ret<0)
        {
            return false;
        }

        change_status += ret;

        //中医治则
        ret = save_rec_hist("中医治则", ui->pt_treat_tr->toPlainText(),
                            qrm->value("treat_tr").toString(),
                            tmstmp, mpPatientInfo["clinic_code"]);
        if(ret<0)
        {
            return false;
        }

        change_status += ret;

        sq = " update ys_bz_e_rec e set ";
        sq += " tmstmp = now(),";//

        if(change_status > 0)
        {
            //关键内容发生变化，保存新检验码
            sq += " sm3 = '" + calc_sm3 + "',";//
        }

        sq += " hzzs = '" + ui->leHzzs->text().trimmed() + "',";//患者主诉
        sq += " trustee_name = '" + ui->leTrustee->text().trimmed() + "',";//代取药人
        sq += " trustee_tel = '" + ui->leTrusteeP->text().trimmed() + "',";//
        sq += " trustee_certno = '" + ui->leTrusteeI->text().trimmed() + "',";//
        sq += " rlts = '" + ui->cbbTrusteeRlt->currentText() + "',";//代取药人关系
        sq += " xbs = '" + ui->pt_current_symp->toPlainText().trimmed() + "',";//现病史
        sq += " person_hist = '" + ui->pt_person_history->toPlainText().trimmed() + "',";//个人史
        sq += " menstr_hist = '" +ui->le_menstr->text().trimmed() + "',";//月经史
        sq += " family_hist = '" +ui->pt_family_history->toPlainText().trimmed() + "',";//
        sq += " jws = '" + ui->leJws->text().trimmed() + "',";//
        sq += " gms = '" + ui->leGms->text().trimmed() + "',";//
        sq += " ys = '" + pub::usr_name + "',";//
        sq += " yz = '" + ui->pt_medical_advice->toPlainText() + "',";//
        sq += " tgjc = '" + ui->pt_body_check->toPlainText().trimmed() + "',";//
        sq += " tgjc_tr = '" + ui->pt_body_check_tr->toPlainText().trimmed() + "',";//
        sq += " jzyy = '" + ui->cbbReason->currentText() + "',";//
        sq += " jzyyc = '" + getIcpcCode(ui->cbbReason->currentText()) + "',";//
        sq += " diag_date = curtime(),";//
        sq += " zljl = '" + ui->cbb_conclusion->currentText() + "',";//

        //"zd1,zd2,zd3,zd1c,zd2c,zd3c,"//西医诊断
        sq += " zd1 = '" + ui->cbbDiag1->currentText() + "',";//
        sq += " zd2 = '" + ui->cbbDiag2->currentText() + "',";//
        sq += " zd3 = '" + ui->cbbDiag3->currentText() + "',";//
        sq += " zd1c = '" + getNatCode(ui->cbbDiag1->currentText(), "2") + "',";//
        sq += " zd2c = '" + getNatCode(ui->cbbDiag2->currentText(), "2") + "',";//
        sq += " zd3c = '" + getNatCode(ui->cbbDiag3->currentText(), "2") + "'";//

        if(!ui->rb_mode_med->isChecked())
        {
            //中医相关
            //"zyzd1,zyzd2,zyzd3,zyzd1c,zyzd2c,zyzd3c,"//中医诊断
            sq += " , zyzd1 = '" + ui->cbb_tr_diag1->currentText() + "',";//
            sq += " zyzd2 = '" + ui->cbb_tr_diag2->currentText() + "',";//
            sq += " zyzd3 = '" + ui->cbb_tr_diag3->currentText() + "',";//
            sq += " zyzd1c = '" + getNatCode(ui->cbb_tr_diag1->currentText(), "8") + "',";//
            sq += " zyzd2c = '" + getNatCode(ui->cbb_tr_diag2->currentText(), "8") + "',";//
            sq += " zyzd3c = '" + getNatCode(ui->cbb_tr_diag3->currentText(), "8") + "',";//
            //"zyzh1,zyzh2,zyzh3,zyzh1c,zyzh2c,zyzh3c,"//中医证候
            sq += " zyzh1 = '" + ui->cbb_tr_symptom1->currentText() + "',";//
            sq += " zyzh2 = '" + ui->cbb_tr_symptom2->currentText() + "',";//
            sq += " zyzh3 = '" + ui->cbb_tr_symptom3->currentText() + "',";//
            sq += " zyzh1c = '" + getNatCode(ui->cbb_tr_symptom1->currentText(), "9") + "',";//
            sq += " zyzh2c = '" + getNatCode(ui->cbb_tr_symptom2->currentText(), "9") + "',";//
            sq += " zyzh3c = '" + getNatCode(ui->cbb_tr_symptom3->currentText(), "9") + "',";//

            sq += " similar_syndrom = '" +ui->pt_similar_syndrom->toPlainText().trimmed() + "',";//类证
            sq += " treat_tr = '" +ui->pt_treat_tr->toPlainText().trimmed() + "',";//中医治则

            //"zybz "//中医辩证
            sq += " zybz = '" + ui->pt_tr_diag->toPlainText() + "'";//辩证依据
        }
        sq += " where clinic_code = '" + mpPatientInfo["clinic_code"] + "' ";

        qDebug()<<"修改保存病志记录："<<sq;

        if(!qrm->exec(sq))
        {
            QMessageBox::information(this, "注意", "保存病志记录失败！\nerrmsg : " + qrm->lastError().text());
            qDebug()<<qrm->lastError().text();
            return false;
        }

    }

    if(change_status > 0)
    {
        //关键内容发生变化，保存 sm3
        sq = "insert into ys_bz_e_rec_sm3 (tmstmp, tmstmp_count, sm3_code, clinic_code)"
             " values(now(), %1, '%2', '%3')" ;
        sq = sq.arg(tmstmp).arg(calc_sm3).arg(mpPatientInfo["clinic_code"]);
        qDebug()<<"save ys_bz_e_rec_sm3 : "<<sq<<"\n";

        if(!qrm->exec(sq))
        {
            QMessageBox::information(this, "注意", "保存 sm3 校验码失败！ ");
            qDebug()<<"保存 sm3 校验码失败！\n";
            return false;
        }
    }
    return true;
}


int Form_ys_bzgl::save_rec_hist(QString fld_name, //字段名
                                      QString fld_new, //新值
                                      QString fld_old, //旧值
                                      QString tmstmp, //时间戳
                                      QString clinic_code)//
{

    if(fld_new == fld_old)
    {
        return 0;   //未变化
    }

    QString str_sql;
    str_sql = "insert into ys_bz_e_rec_hist"
              "(clinic_code,oper_time,tmstmp_count,fld_name,fld_new,fld_old)"
              "values("
              "'%1',"
              "now(),"//oper_time
              "%2,"//tmstmp_count
              "'%3',"//fld_name
              "'%4',"//fld_new
              "'%5'"//fld_old
              ")";
    str_sql = str_sql.arg(clinic_code)
            .arg(tmstmp)
            .arg(fld_name)
            .arg(fld_new)
            .arg(fld_old);
    qDebug()<<"保存历史记录："<<str_sql<<"\n";

    if(qrmt->exec(str_sql))
    {
        return 1;   //保存成功
    }
    else
    {
        return -1;  //保存失败
    }

}

void Form_ys_bzgl::on_pb_5465_clicked()
{
    sq = " SELECT medOrgOrd FROM zjzf_5465_push "
         " where clinic_code = '%1' "
         " and push_state = '0'"
         " and date(push_time) = curdate()";
    sq = sq.arg(mpPatientInfo["clinic_code"]);
    qDebug()<<"提取可进行诊间推送的数据："<<sq<<"\n";
    qrm->exec(sq);
    bool no_push = true;

    while(qrm->next())
    {
        no_push = false;

        QString id = qrm->value(0).toString();

        if(push_5465(id))
        {
            QMessageBox::information(this, "注意", id + " 诊间支付消息已经推送！ ");
        }
        else
        {
            QMessageBox::warning(this, "注意", id + " 诊间支付消息推送失败！ ");
        }
    }

    if(no_push)
    {
        QMessageBox::information(this, "注意", "无可推送的诊间支付消息！ ");
    }
}

QString Form_ys_bzgl::get_cur_drug_left(QString card_no, QString dt)
{

    //计算历史开药数据
    //sq += " and fee.item_code = '" + index.siblingAtColumn(13).data().toString() + "'";
    QString ret = "";

    qDebug()<<"计算历史开药数据\n";

    sq = " select distinct fee.item_code, fee.item_name"
         " from fin_opb_feedetail fee "
         " where fee.card_no = '%1' and fee.cancel_flag = '1' "
         " and fee.oper_date > to_date('%2','yyyy-mm-dd') - 90 "
         " and trunc(fee.oper_date) <= to_date('%2','yyyy-mm-dd')"
         " and fee_code in ('001','002')";
    sq = sq.arg(card_no).arg(dt);
    qDebug()<<"截止日期前90日内用药项目："<<sq<<"\n";
    qro->exec(sq);

    while(qro->next())
    {
        //sq += " and fee.item_code = '" + index.siblingAtColumn(13).data().toString() + "'";
        QString name = qro->value(1).toString();
        QString code = qro->value(0).toString();
        qDebug()<<name<<" 计算历史开药数据\n";
        sq = " select fee.days, fee.oper_date "
             " from fin_opb_feedetail fee "
             " where fee.card_no = '%1' and fee.cancel_flag = '1' "
             " and fee.oper_date > to_date('%2','yyyy-mm-dd') - 90 "
             " and trunc(fee.oper_date) <= to_date('%2','yyyy-mm-dd')"
             " and fee.item_code = '%3'";

        //处方项目关联的挂号记录状态应为有效
        sq += " and (select reg.valid_flag from fin_opr_register reg"
              "      where reg.clinic_code = fee.clinic_code"
              "      and rownum = 1 ) = '1' ";

        sq += " order by fee.oper_date desc ";

        sq = sq.arg(card_no).arg(dt).arg(code);
        qrot->exec(sq);
        qDebug()<<"检索90天累计用量："<<sq<<"\n";

        int count = 0;
        int maxCount = 0;  //最大可用处方天数
        int realDays = 0;   //处方日期至当前日期的天数
        QDate curD, RecipeD,maxD;

        curD = QDate::fromString(dt, "yyyy-MM-dd");
qDebug()<<"curD : "<<curD;
        while(qrot->next())
        {
            RecipeD = qrot->value(1).toDate();
            count += qrot->value(0).toInt();
            realDays = RecipeD.daysTo(curD);

            if(count - realDays > maxCount)
            {
                //保存最大可用处方天数的处方日期
                maxCount = count - realDays;
                maxD = RecipeD;
            }
        }

        if(ret.isEmpty())
        {
            ret = name + " " + QString::number(maxCount) + "天";
        }
        else
        {
            ret += "\n" + name + " " + QString::number(maxCount) + "天";
        }
    }

    return ret;

}
void Form_ys_bzgl::on_pb_drug_remain_clicked()
{
    QString msg = get_cur_drug_left(mpPatientInfo["card_no"], QDate::currentDate().toString("yyyy-MM-dd"));
    if(msg.isEmpty())
    {
        QMessageBox::information(this, "药品余量查询结果", "当前患者无存量药品！");
    }
    else
    {
        QMessageBox::information(this, "药品余量查询结果", msg);
    }
}

void Form_ys_bzgl::on_pb_drug_remain_1_clicked()
{
    on_pb_drug_remain_clicked();
}
